I'm having trouble using arrayFilters in MongoDB currently I have a document that looks like this
{
"_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
}
I want to update the status of the recipient with the faculty_number of 111 to "Seen". Based on the docs , I can use $[identifier] and arrayFilters
to specify which one I want to update.
I'm currently using this query:
db.getCollection('memos').findOneAndUpdate(
{"_id": ObjectId("5a5f814487c320156094c144")},
{$set: {"recipients.$[elem].status": "Seen"}},
{arrayFilters: [{"elem.faculty_number": 111}]}
)
But I get this error
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
I just followed the example that was presented in the docs .
You need to add the index of "faculty_number" : 111,
then update the sub-document using positional
db.memos.update(
{
"_id": ObjectId("5a5f814487c320156094c144"),
"recipients.faculty_number": 111
},
{
$set: {
"recipients.$.status": "Sent"
}
}
)
ps: cant try findOneAndUpdate - not a function in my cli
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.