《微信小程序开发从入门到实战》学习三十九

4.2 云开发JSON数据库

4.2.10 查询数组和对象

1.匹配记录中的嵌套字段

    db.collection('testOne').add({data:{style:{color:'red'}}})

    db.collection('testOne').add({data:{style:{color:'blue'}}})

插入两天记录,如果希望查询style.color为blue的记录,有两种查询方式:

//方式一:传入相同结构的对象作为查询条件

    db.collection('testOne').where({

      style: {color: 'blue'}

    }).get().then(res => {

      console.log(res.data)

    })

//方式二:使用“点表示法”查询

db.collection('testOne').where({

  'style.color': 'blue' //使用“点表示法”查询,对象的属性必须用引号引起来,否则有语法错误

}).get().then(res => {

  console.log(res.data)

})

2.匹配数组

db.collection('testOne').add({data:{data:[1,2,3]}})

想筛出这条记录,完全可以传入相同的数组来筛选:

db.collection('testOne').where({

  data: [1,2,3]

}).get().then(res => {

  console.log(res.data)

})

2.匹配数组中的元素,通过数组中的元素找到数组所在的记录,代码如下:

db.collection('testOne').where({

  data: 2

}).get().then(res => {

  console.log(res.data)

})

3.匹配数组第n项元素

想找到数组第n项等于某值的数组所在的记录,用“字段名.n”为key进行匹配:

//找出data数组第2项的值为2的记录

db.collection('testOne').where({

  'data.1': 2 //数组下标从0开始

}).get().then(res => {

  console.log(res.data)

})

4.结合查询指令对数组进行匹配

使用查询指令筛选出数组中存在满足给定比较条件的记录。示例代码如下:

//找出所有data字段的数组值中存在包含大于1的值的记录

   db.collection('testOne').where({

    data: db.command.gt(1)

  }).get().then(res => {

    console.log(res.data)

  })

5.匹配多重嵌套的数组的对象

db.collection('testOne').add({data:{test:{objects: [{data:[1,2,3]},{data:[5,6,7]}]}}})

找出集合中所有满足test.objects数组第一个元素的data的第三项等于3的记录,代码如下:

  db.collection('testOne').where({

    'test.objects.0.data.2': 3

  }).get().then(res => {

    console.log(res.data)

  })

在嵌套查询可以不指定数组的下标,示例代码如下:

//找出集合所有满足test.objects数组中任意一项data字段包含2的记录

   db.collection('testOne').where({

    'test.objects.data': 2

  }).get().then(res => {

    console.log(res.data)

  })

你可能感兴趣的:(学习)