参考:

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日"}})

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐