Update two separate arrays in a document with one update call in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $push operator for this. Let us first create a collection with documents

>db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152815e86fd1496b38b8")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152d15e86fd1496b38b9")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b153315e86fd1496b38ba")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58
   ],
   "StudentSecondGameScore" : [
      78
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}

Following is the query to push two separate arrays in one update call in MongoDB

> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
   StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the value is pushed in two separate arrays or not

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

This will produce the following output

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58,
      45
   ],
   "StudentSecondGameScore" : [
      78,
      99
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}
raja
Published on 11-Apr-2019 11:41:43
Advertisements