MongoDB concurrent update with sub collection?

MongoDBDatabaseBig Data Analytics

For update, simply use update(). Use the $push operator to append a specified value and the dot notation to reach the sub collection and update inside update().

Let us create a collection with documents −

> db.demo547.insertOne(
... {
...    Name : "Chris",
...    Test :
...    {
...       "FirstTest" :
...       {
...          Scores: [56,29,76]
...       },
...       "SecondTest" :
...       {
...          Scores: [98,91,78]
...       }
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8e2d579e5f92834d7f05dd")
}

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

> db.demo547.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : {
"Scores" : [ 56, 29, 76 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }

Following is the query for concurrent update with subcollection −

> db.demo547.update({"Name":"Chris"}, { $push:{ "Test.FirstTest.Scores" : 99}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo547.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : {
"Scores" : [ 56, 29, 76, 99 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }
raja
Published on 14-May-2020 10:38:41
Advertisements