这是我在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
}
]
},
}
我需要更新内部rooms数组中的对象。我尝试了一个查询,该查询选择了一个匹配元素,没有语法错误,但是出现错误:
“ errmsg”:“字段'calendar.0.rooms.0.price'必须是一个数组,但是 在文档{_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中找到的一些参考资料,但没有帮助: Updating a Nested Array with MongoDB
答案 0 :(得分:2)
您可以使用以下查询
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") }
]
}
)
我将在稍后的解释中更新我的答案