How to create a new object and get its saved object in MongoDB?


For this, use save() in MongoDB. Following is the syntax −

var anyVaribaleName=yourValue
db.anyCollectionName.save(yourVariableName);
yourVariableName;

Let us first create an object for our example −

> var studentDetails={"StudentName":"Chris","ListOfMarks":[56,78,89],"ListOfSubject":["MySQL","Java","MongoDB"]};

Let us save the above created object “studentDetails” −

> db.demo40.save(studentDetails);
WriteResult({ "nInserted" : 1 })

Let us display the value −

> studentDetails;

This will produce the following output −

{
   "StudentName" : "Chris",
   "ListOfMarks" : [
      56,
      78,
      89
   ],
   "ListOfSubject" : [
      "MySQL",
      "Java",
      "MongoDB"
   ],
   "_id" : ObjectId("5e177757cfb11e5c34d898e2")
}

Updated on: 02-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements