How to update after aggregate in MongoDB?


To update documents, you cannot use aggregation pipeline. You can use update(). Let us first create a collection with documents −

> db.demo376.insertOne(
...    {
...
...       "id" :101,
...
...       "details" : [
...          {
...             Name:"Chris",
...             Age:21,
...             Score:45
...          },
...          {
...             Name:"David",
...             Age:23,
...             Score:67
...          },
...          {
...             Name:"Bob",
...             Age:20,
...             Score:54
...          }
...       ]
...    }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a71b92ae06a1609a00b0d")
}

Display all documents from a collection with the help of find() method −

> db.demo376.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5a71b92ae06a1609a00b0d"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "Age" : 21,
         "Score" : 45
      },
      {
         "Name" : "David",
         "Age" : 23,
         "Score" : 67
      },
      {
         "Name" : "Bob",
         "Age" : 20,
         "Score" : 54
      }
   ]
}

Following is the query to update −

> db.demo376.update(
...    {"id" :101},
...    {$inc:{"details.$[d].Age":3}},
...    {arrayFilters: [ {$and:[{"d.Age": 21},{"d.Score": {"$gt":40}} ]}] }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo376.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5a71b92ae06a1609a00b0d"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "Age" : 24,
         "Score" : 45
      },
      {
         "Name" : "David",
         "Age" : 23,
         "Score" : 67
      },
      {
         "Name" : "Bob",
         "Age" : 20,
         "Score" : 54
      }
   ]
}

Updated on: 02-Apr-2020

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements