MongoDB query to add a document in an already created collection


To add a document in an already created collection, use $push in MongoDB. Let us create a collection with documents −

> db.demo177.insertOne(
   { "Id": "101", "details": [  
      { "StudentName": "Chris",  "Scores": [67, 71, 74], "SubjectName": ["MySQL", "Java"]  },
      { "StudentName": "David", "Scores": [89,98,45], "SubjectName": ["PL/SQL", "C"] } ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e384b2b9e4f06af551997f4")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e384b2b9e4f06af551997f4"),
   "Id" : "101",
   "details" : [
      {
         "StudentName" : "Chris",
         "Scores" : [ 67, 71, 74 ],
         "SubjectName" : [ "MySQL", "Java" ]
      },
      {
         "StudentName" : "David",
         "Scores" : [ 89, 98, 45 ],
         "SubjectName" : [ "PL/SQL", "C" ]
      }
   ]
}

Following is the query to add a document in an already created collection −

> db.demo177.update({"Id": "101"},
...{
...   $push: {
...      "details": {
...         "StudentName": "Chris",
...         "Scores": [90, 91, 94],
...         "SubjectName": ["MongoDB", "SQL Server"]
...      }
...   }
...});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e384b2b9e4f06af551997f4"),
   "Id" : "101",
   "details" : [
      {
         "StudentName" : "Chris",
         "Scores" : [ 67, 71, 74 ],
         "SubjectName" : [ "MySQL", "Java" ]
      },
      {
         "StudentName" : "David",
         "Scores" : [ 89, 98, 45 ],
         "SubjectName" : [ "PL/SQL", "C" ]
      },
      {
         "StudentName" : "Chris",
         "Scores" : [ 90, 91, 94 ],
         "SubjectName" : [ "MongoDB", "SQL Server" ]
      }
   ]
}

Updated on: 27-Mar-2020

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements