mongodb 查询更新选择嵌套字段

编程入门 行业动态 更新时间:2024-10-22 11:28:18
本文介绍了mongodb 查询更新选择嵌套字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我在 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 查询更新选择嵌套字段

本文发布于:2023-11-22 20:42:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字段   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!