1

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?

1
  • Can you show sample of your data? _id is the field mongoDB uses and it is auto added for every element in the array so there is no need to se tit manually. Commented Oct 22, 2018 at 6:05

2 Answers 2

1

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 "".

Sign up to request clarification or add additional context in comments.

Comments

0

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}
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.