MongoDB update multiple subdocuments with or query

前端 未结 5 862
时光取名叫无心
时光取名叫无心 2021-01-27 14:50

I want to make an update query for multiple subdocuments at once. I will be setting all the subdocuments statuses to passive where they satisfy the condition I give on query. <

5条回答
  •  迷失自我
    2021-01-27 15:23

    You got this error

    The positional operator did not find the match needed from the query

    because of your second query matched with multiple sub-document. Currently it is not possible to use the positional operator to update all items in an array using positional operator.

    so to solve your problem you can follow this process

    1. Find document using _id and to find sub document using $elemMatch and then

    2. update each sub document and save document again

    can try like this:

    db.deduplications.find(  
    { $or: [ {
             "_id": ObjectId("583fc558668bde730a460e11") , 
            "DeviceVersionPairs":{
                $elemMatch:{ "DeviceId": ObjectId("5822d0606bfdcd6ec407d9b9") , 
                "CloudFolderId": ObjectId("5823110e6bfdd46ec4357582") ,
                "DeviceVersionPairs.CloudFileId": ObjectId("582311168cd396223499942a") ,
                "DeviceVersionPairs.VersionId": ObjectId("582311168cd396223499942b") }}
        } ,   
        { 
            "_id": ObjectId("583fc558668bde730a460e11") , 
            "DeviceVersionPairs":{
                $elemMatch:{ "DeviceId": ObjectId("56dfe1356caaea14a819f1e4") , 
                "CloudFolderId": ObjectId("583fb4bc6e7f341874f13bfc") , 
                "CloudFileId": ObjectId("583fb539e015b8a53fb71872") , 
                "VersionId": ObjectId("583fb4ca6e7f331874213584") }}
        } ] 
    }).forEach(function (doc) {
        doc.DeviceVersionPairs.forEach(function (device) {
          device.status = 'passive';
        });
        db.deduplications.save(doc);
     });
    

提交回复
热议问题