Cannot apply positioning operator without matching query field containing array

I have the following document:

{ "id" : "1",
"name": "Paul",
"a": { "b" : [{"name" : "laura", "lastname" : "Palmer"}]}
}

      

Now I want to update every last name in b.

I've tried this:

    db.organizations.update({"name" : "Paul", "a.b" : {$exists: true}},
{ "$set" : {"a.b.$.lastname" : "no_lastname"}});

      

But I understand: It is not possible to apply the positioning operator without the corresponding query field containing the array.

Anyone have an idea what I should be doing?

+3


source to share


1 answer


You can use the cursor method cursor.forEach()

in mongo shell to accomplish this:



db.organizations.find({"name" : "Paul", "a.b" : {$exists: true}}).forEach(function(doc) {
    array = doc.a.b; 
    array.forEach(function(elem) {
        elem.lastname="no_lastname"
    }); 
    db.organizations.update({_id:doc._id}, {$set:{"a.b":array}}); 
})

      

+2


source







All Articles