简体   繁体   English

MongoDB-使用arrayFiters的findOneAndUpdate

[英]MongoDB - findOneAndUpdate with arrayFiters

I'm having trouble using arrayFilters in MongoDB currently I have a document that looks like this 我在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
}

I want to update the status of the recipient with the faculty_number of 111 to "Seen". 我想将faculty_number为111的接收者的状态更新为“ Seen”。 Based on the docs , I can use $[identifier] and arrayFilters to specify which one I want to update. 根据文档 ,我可以使用$[identifier] and arrayFilters来指定要更新的文件。

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 . 我只是按照docs中提供的示例进行操作。

You need to add the index of "faculty_number" : 111, then update the sub-document using positional 您需要添加"faculty_number" : 111,的索引"faculty_number" : 111,然后使用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 ps:不能尝试findOneAndUpdate-不是我的CLI中的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM