微信小程序云开发-database查询和修改常用语句总结

database查询和修改常用语句总结

一、数据如下:

[{
    "_id": "54ad1eea62207fbd140f6ca118812490",
    "address": {
        "info": "闲林街道",
        "city": "杭州市"
    },
    "age": 18.0,
    "name": "张三",
    "sex": "男",
    "test": [{
        "key1": 11.0,
        "key2": "value2222",
        "key3": 33.0
    }, {
        "key4": 44.0,
        "key2": "value2222"
    }],
    "test1": {
        "key1": "obj1",
        "key2": "obj2"
    },
    "test2": ["2222222222", "2222222222"],
    "root": {
        "objects": [{
            "numbers": [10.0, 80.0, 30.0]
        }]
    }
}]

二、查询与更新几种常用用法汇总

const command = db.command

/**
 * 查询test:[{key2:11},{key2:22}]
 */

//查询key=222的项
// db.collection('students').where({
// test: command.elemMatch({key2: 222})
// }).get()


//查询key2的值>200的项
// const command = db.command
// db.collection('students').where({
// test: command.elemMatch({key2: command.gt(200)})
// }).get()

//查询key=222的项并修改为333
// const command = db.command
// db.collection('students').where({
//   test: command.elemMatch({ key2: 222 })
// }).update({
//   data: {
//     'test.$[].key2': 333
//   }
// })


/**
 * 查询test2
 */

//让所有 test2 中的第一个 obj222222 的元素更新
//为 111111111
// db.collection('students').where({
//   test2:'obj222222'
// }).update({
//   data:{
//     'test2.$':'111111111'
//   }
// })


//更新test2数组中所有元素为2222222
// db.collection('students').where(
//   {}
// ).update({
//   data:{
//     'test2.$[]':'2222222222'
//   }
// })



//更新test数组中所有key2元素为value22222
// db.collection('students').where(
//   {}
// ).update({
//   data:{
//     'test.$[].key2':'value2222'
//   }
// })

//匹配多重嵌套的数组和对象

//两种写法都可以
// db.collection('students').where(
//   {
//     'root.objects.0.numbers.1': 20
//   }
// ).get()


// db.collection('students').where({
//   'root.objects.numbers': 10
// }).get()

//更新
// db.collection('students').where({

// }).update({
//   data: {
//     'root.objects.0.numbers.1': 80
//   },
// })

3、总结:

对于不经常写查询语句的程序猿来说写复杂的语句有点难度的,特别是数组和对象的多层嵌套来说更加困难,还是要从基本去入手,把常见的用法总结出来就好了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容