Update an array of strings nested within an array of objects in MongoDB

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo411.aggregate(
...    [
...       {$project : {
...          _id : 0,
...          Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}}
...          }
...       }
...    ]
... )
{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }
> db.demo412.insertOne(
...    {
...       "Information1" : [
...          {
...             "Information2" : [
...                "John",
...                "David"
...             ]
...          },
...          {
...             "Information2" : [
...                "Mike"
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70f38b15dc524f70227683")
}

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

> db.demo412.find();

This will produce the following output −

{ "_id" : ObjectId("5e70f38b15dc524f70227683"), "Information1" : [ { "Information2" : [ "John", "David" ] }, { "Information2" : [ "Mike" ] } ] }

Following is the query to update an array of strings nested within an array of objects in MongoDB −

> db.demo412.updateMany(
...    { _id: ObjectId("5e70f38b15dc524f70227683") },
...    { $pull : {'Information1.$[].Information2' : "Mike" } }
... );
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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

> db.demo412.find();

This will produce the following output −

{ "_id" : ObjectId("5e70f38b15dc524f70227683"), "Information1" : [ { "Information2" : [ "John", "David" ] }, { "Information2" : [ ] } ] }
raja
Published on 03-Apr-2020 16:51:57
Advertisements