这是我在 mongo 中的文档:
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" : "字段 'calendar.0.rooms.0.price' 必须是一个数组,但是文档 {_id: 中的字符串类型ObjectId('5cd26a886458720f7a66a3b8')}",
"errmsg" : "The field 'calendar.0.rooms.0.price' must be an array but is of type string in document {_id: ObjectId('5cd26a886458720f7a66a3b8')}",
这是我的查询:
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")}]})这是我在 StackOverflow 中找到的一些参考,但没有帮助:使用 MongoDB 更新嵌套数组
this is some reference I found in StackOverflow but not helped: Updating a Nested Array with MongoDB
推荐答案您可以使用下面的查询
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
更多推荐
mongodb 查询更新选择嵌套字段
发布评论