Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb remove field from Array objects all documents?

I have a collection that has documents looks something like this:

 _id : 21353456,
product : "xy",
text : "asdf",
reviews : [
{
     username : "User1",
     userID: 12
     text : "hi",
     },
     {
     username : "User2",
     userID: 123
     text : "hi1",
     }
    ]
}

I want to remove the field in username from the objects in this array.
I tried this
db.collection.update({}, {$unset: {"reviews.username": 1}}, {multi: true})
I tried with even updateMany and it just matchedCouunt and acknowledged.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try using the positional identifier and do something like:

db.collection.update({}, {$unset: {"reviews.$[].username":true}}, {multi:true})

Personally I prefer using the method below:

db.collection.update({"reviews.username": {$exists: true}}, {$unset: {"reviews.$.username":true}}, {multi:true})

Because sometimes you should check if it exists before you do the deleting (this way you won’t get any errors).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading