我在MongoDB中使用arrayFilters时遇到问题,目前我的文档看起来像这样
{
"_id" : ObjectId("5a5f814487c320156094c144"),
"sender_id" : "123",
"iso_number" : "ABC-DEF-123",
"subject" : "Sample Memo",
"content" : "This is a sample memorandum sent through postman.",
"recipients" : [
{
"faculty_number" : 222,
"_id" : ObjectId("5a5f814487c320156094c146"),
"status" : "Sent"
},
{
"faculty_number" : 111,
"_id" : ObjectId("5a5f814487c320156094c145"),
"status" : "Sent"
}
],
"memo_created" : ISODate("2018-01-17T17:00:52.104Z"),
"__v" : 0
}
我想更新收件人的状态,其中faculty_number为111," Seen"。根据{{3}},我可以使用$[identifier] and arrayFilters
来指定我要更新的内容。
我目前正在使用此查询:
db.getCollection('memos').findOneAndUpdate(
{"_id": ObjectId("5a5f814487c320156094c144")},
{$set: {"recipients.$[elem].status": "Seen"}},
{arrayFilters: [{"elem.faculty_number": 111}]}
)
但是我收到了这个错误
Failed to execute script. Error: findAndModifyFailed failed: {
"ok" : 0,
"errmsg" : "cannot use the part (recipients of recipients.$[elem].status) to traverse the element ({recipients: [ { faculty_number: 456, _id: ObjectId('5a5f7c849c70ee3c3c7c28f3'), status: \"Sent\" }, { faculty_number: 789, _id: ObjectId('5a5f7c849c70ee3c3c7c28f2'), status: \"Sent\" } ]})",
"code" : 16837,
"codeName" : "Location16837" } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DBCollection.prototype.findAndModify@src/mongo/shell/collection.js:768:1 DBCollection.prototype.findOneAndUpdate@src/mongo/shell/crud_api.js:823:12 @(shell):1:1
我只是按照docs中提供的示例。
答案 0 :(得分:1)
您需要添加"faculty_number" : 111,
的索引
然后使用位置
db.memos.update(
{
"_id": ObjectId("5a5f814487c320156094c144"),
"recipients.faculty_number": 111
},
{
$set: {
"recipients.$.status": "Sent"
}
}
)
ps:不能尝试findOneAndUpdate - 不是我的cli中的函数