Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update Array Elements matching criteria in a MongoDB document?

Tags:

mongodb

I have a document with an array field, similar to this:

{ 
  "_id" : "....",
  "Statuses" : [
    { "Type" : 1, "Timestamp" : ISODate(...) },
    { "Type" : 2, "Timestamp" : ISODate(...) },
    //Etc. etc.
  ]
}

How can I update a specific Status item's Timestamp, by specifying its Type value?

like image 328
Redth Avatar asked Nov 01 '11 13:11

Redth


People also ask

How do you update an array element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do you update an array?

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values. Copied! const arr = ['zero', 'one', 'two']; arr.

Which of the following act as a placeholder to update the first element that matches the query condition in an update?

Acts as a placeholder to update the first element that matches the query condition.


1 Answers

Starting with MongoDB 3.6, the $[<identifier>] positional operator may be used. Unlike the $ positional operator — which updates at most one array element per document — the $[<identifier>] operator will update every matching array element. This is useful for scenarios where a given document may have multiple matching array elements that need to be updated.

db.yourCollection.update(
  { _id: "...." },
  { $set: {"Statuses.$[element].Timestamp": ISODate("2021-06-23T03:47:18.548Z")} },
  { arrayFilters: [{"element.Type": 1}] }
);

The arrayFilters option matches the array elements to update, and the $[element] is used within the $set update operator to indicate that only array elements that matched the arrayFilter should be updated.

like image 141
M. Justin Avatar answered Sep 22 '22 17:09

M. Justin