简体   繁体   中英

MongoDB update all elements of nested array within all documents

I have a collection (called Clients) which contains multiple documents, each one representing a client. Each client document contains an array of phoneNumber documents. I would like to update all phoneNumber documents in all the client documents my collection to add a readOnly attribute to each phoneNumber document.

The challenge is that some of the phoneNumber documents have a readOnly attribute which I think is throwing me off...

Example JSON document below;

{
    "_id" : ObjectId("5baa8e5da61b7842284937b7"),
    "clientID" : "00001",
    "firstName" : "Jonathan",
    "middleName" : "Herbert",
    "lastName" : "Alexander",
    "dateOfBirth" : "1965-04-04",
    "email" : "jonalex@hcare.com",
    "phoneNumbers" : [ 
        {
            "phoneID" : "001",
            "number" : "(404) 242-5939",
            "phoneType" : "HOME"
        },
        {
            "phoneID" : "001",
            "number" : "(404) 242-5939",
            "phoneType" : "HOME"
            "readOnly" : true
        },
        {
            "phoneID" : "001",
            "number" : "(404) 242-5939",
            "phoneType" : "HOME"
        }
    ],
    "gender" : "M"
}

In this example, I would like all phoneNumber documents to have the readOnly:false attribute.

I have tried using the following...

db.Clients.update(
   {},
   { $set: { "phoneNumbers.$[].readOnly" : true } },
   { multi: true}
)

...but it is giving me an error about not being about to use the part to traverse the element, so I am stuck.

How can I update all the documents in this collection to add the readOnly field to all elements in each documents' nested phoneNumbers array?

Here would be an example query.
This will push the desired element onto each phone numbers document. If you are not attempting to

var results = db.Clients.find({"phoneNumbers.readOnly" : {$exists : false } });
results.forEach(function (result){
    result.phoneNumbers.forEach(function (doc){
       doc.push({"phoneNumbers.$[].readOnly" : true })
    })
});

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.

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