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

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



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" : [ ] } ] }
Updated on: 2020-04-03T13:22:52+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements