mongodb query update select nested fields

蓝咒 提交于 2021-01-27 19:21:55

问题


this is my document in mongo:

"calendar": {
        "_id": "5cd26a886458720f7a66a3b8",
        "hotel": "5cd02fe495be1a4f48150447",
        "calendar": [
            {
                "_id": "5cd26a886458720f7a66a413",
                "date": "1970-01-01T00:00:00.001Z",
                "rooms": [
                    {
                        "_id": "5cd26a886458720f7a66a415",
                        "room": "5cd17d82ca56fe43e24ae5d3",
                        "price": "",
                        "remaining": 0,
                        "reserved": 0
                    },
                    {
                        "_id": "5cd26a886458720f7a66a414",
                        "room": "5cd17db6ca56fe43e24ae5d4",
                        "price": "",
                        "remaining": 0,
                        "reserved": 0
                    }
                ]
            },
   }

I need to update the objects in the inner rooms array . I tried a query that selects a matching element no syntax error but an error comes in:

"errmsg" : "The field 'calendar.0.rooms.0.price' must be an array but is of type string in document {_id: ObjectId('5cd26a886458720f7a66a3b8')}",

and this my query:

db.calendars.updateOne({_id:ObjectId("5cd26a886458720f7a66a3b8"), 
 "calendar":{"$elemMatch":{"_id":ObjectId("5cd26a886458720f7a66a413"),"rooms._id":
 ObjectId("5cd26a886458720f7a66a415")}}}, 
{"$push":{"calendar.$[outer].rooms.$[inner].price":"100000"}}, {"arrayFilters":[{"outer._id":ObjectId("5cd26a886458720f7a66a413")},{"inner._id":ObjectId("5cd26a886458720f7a66a415")}]})

this is some reference I found in StackOverflow but not helped: Updating a Nested Array with MongoDB


回答1:


You can use below query

db.getCollection("test").updateOne(
  {
    "_id": ObjectId("5cd26a886458720f7a66a3b8"),
    "calendar.calendar": {
      "$elemMatch": {
        "_id": ObjectId("5cd26a886458720f7a66a413"),
        "rooms._id": ObjectId("5cd26a886458720f7a66a415")
      }
    }
  },
  { "$set": { "calendar.calendar.$[outer].rooms.$[inner].price": "100000" } },
  {
    "arrayFilters": [
      { "outer._id": ObjectId("5cd26a886458720f7a66a413") },
      { "inner._id": ObjectId("5cd26a886458720f7a66a415") }
    ]
  }
)

I will update my answer with some explanation afterward



来源:https://stackoverflow.com/questions/56035093/mongodb-query-update-select-nested-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!