简体   繁体   中英

Updating all elements in a mongodb embedded array

I have a User document, with an array of Notes (objects) inside it. I'm trying to set a new field (_id) on all items in the array. But It's not touching anything. This is my current code, am I missing anything?

 db.users.update(
  {'notes.added': '2018-10-22 04:42:45.336Z'},
  {'$set': {'notes.$._id': new ObjectId()}},
  {multi: true}
);

Also I'm targeting all notes, where added equals that date, is it possible to target ALL notes without specifying a parameter?

You need to include only the array in the query parameter. Using the property like notes.added will not work. The $ operator needs the array in query operator to iterate.

db.users.update({notes:{$exists: true}}, {$set:{"notes.$._id": new ObjectId()}}, {multi:true});

Hope it helps.

Edit1: if you have multiple documents and you want to edit all arrays in all documents, you need to use updateMany like so:

db.users.updateMany({notes:{$exists: true}}, {$set:{"notes.$[elem]._id": new ObjectId()}},{arrayFilters:[{"elem.a" : {$gte: 0}}]});

where arryFilters is a filter on elements of array. This query will update all arrays which have property a's value greater than or equal to 0. When doing so, you can use notes.property in query as well. just enclose it in "".

If you will want to update all document notes array that have minimum one element object then also you have need to code like that

db.users.update(
    {"notes": { $exists: true, $not: {$size: 0} }}, 
    {'$set': {'notes.$._id': new ObjectId()}}, 
   {multi: true}

);

With added date query just add your condition like that

db.users.update(
        {"notes": { $exists: true, $not: {$size: 0} }, 'notes.added': '2018-10-22 04:42:45.336Z'}, 
        {'$set': {'notes.$._id': new ObjectId()}}, 
       {multi: 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