Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new field to all documents in a nested array

Tags:

mongodb

I have a database of person documents. Each has a field named photos, which is an array of photo documents. I would like to add a new 'reviewed' flag to each of the photo documents and initialize it to false.

This is the query I am trying to use:

db.person.update({ "_id" : { $exists : true } }, {$set : {photos.reviewed : false} }, false, true)

However I get the following error:

SyntaxError: missing : after property id (shell):1

Is this possible, and if so, what am I doing wrong in my update?

Here is a full example of the 'person' document:

{
"_class" : "com.foo.Person",
"_id" : "2894",
"name" : "Pixel Spacebag",
"photos" : [
    {
        "_id" : null,
        "thumbUrl" : "http://site.com/a_s.jpg",
        "fullUrl" : "http://site.com/a.jpg"
    },
    {
        "_id" : null,
        "thumbUrl" : "http://site.com/b_s.jpg",
        "fullUrl" : "http://site.com/b.jpg"
    }]
}

Bonus karma for anyone who can tell me a cleaner why to update "all documents" without using the query { "_id" : { $exists : true } }

like image 433
Michael Peterson Avatar asked Mar 13 '12 01:03

Michael Peterson


1 Answers

For those who are still looking for the answer it is possible with MongoDB 3.6 with the all positional operator $[] see the docs:

db.getCollection('person').update(
   {},
   { $set: { "photos.$[].reviewed" : false } },
   { multi: true}
)
like image 110
zstate Avatar answered Oct 11 '22 13:10

zstate