MongoDB三 之 Array数组 /Object对象 的特殊操作

本文通过两个示例演示了在MongoDB中对数组和嵌套对象的查询与更新操作。在`test_array_object`集合中,展示了如何根据数组元素位置查找和更新数据;在`test_array_object2`集合中,说明了如何对包含复杂对象的数组进行条件筛选并更新特定字段。内容涵盖$gt匹配符、$inc和$set更新操作。
摘要由CSDN通过智能技术生成

参考:

MongoDB三 之 Array Object 的特殊操作

demo1:

db.createCollection("test_array_object")

db.test_array_object.insertMany([
  {
    "name" : "xq1",
    "price" : [
        19800,
        19500,
        19000,
        18800
    ],
    "other" : {
      "start" : "2018年8月1日",
      "start_time" : "08:30",
      "count" : 150
    }
  },  
  {
    "name" : "xq2",
    "price" : [
        29800,
        29500,
        29000,
        28800
    ],
    "other" : {
      "start" : "2000年8月1日",
      "start_time" : "08:30",
      "count" : 200
    }
  }
])

# 数组
db.test_array_object.find({"price.1":19500}).pretty()
db.test_array_object.find({"price.2":{$gt:20000}}).pretty()
# "price.2"代指的是 Array 中第3个元素
# 对象
db.test_array_object.find({"other.count":150}).pretty()

demo2 :

db.createCollection("test_array_object2")

db.test_array_object2.insertMany([
    {
      "name" : "xq1",
      "price" : [
        {
            "start" : "2018年8月1日",
            "start_time" : "08:30",
            "count" : 150
        },
        {
            "start" : "2018年8月2日",
            "start_time" : "09:30",
            "count" : 160
        },
        {
            "start" : "2018年8月3日",
            "start_time" : "10:30",
            "count" : 170
        },
        {
            "start" : "2018年8月4日",
            "start_time" : "11:30",
            "count" : 180
        }
    ]
    }
])

  
db.test_array_object2.find({}).pretty() 


# 1.把count 大于 175 的field  加 15
db.test_array_object2.update({"price.count":{$gt:175}},{$inc:{"price.$.count":15}})

# 2. 把 count 大于 180 的 start 改为 "2018年8月10日"
db.test_array_object2.update({"price.count":{$gt:180}},{$set:{"price.$.start":"2018年8月10日"}})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值