How to get a saved object in MongoDB?

To get a saved object in MongoDB, you can retrieve it from the database using the find() method or access it directly from the JavaScript variable if it's still in memory during the same session.

Syntax

// Access from variable (same session)
variableName;

// Retrieve from database
db.collection.find(query);
db.collection.findOne(query);

Sample Data

Let us first create a variable and save it to the database ?

var studentDetails = {
    "StudentFirstName": "Chris",
    "StudentLastName": "Brown",
    "StudentAge": 24
};
db.demo45.save(studentDetails);
WriteResult({ "nInserted" : 1 })

Method 1: Access from Variable (Same Session)

You can directly access the saved object from the variable ?

studentDetails;
{
    "StudentFirstName" : "Chris",
    "StudentLastName" : "Brown",
    "StudentAge" : 24,
    "_id" : ObjectId("5e25dab4cfb11e5c34d898ec")
}

Method 2: Retrieve from Database

To get the saved object from the database collection ?

db.demo45.find();
{
    "_id" : ObjectId("5e25dab4cfb11e5c34d898ec"),
    "StudentFirstName" : "Chris",
    "StudentLastName" : "Brown",
    "StudentAge" : 24
}

Method 3: Find Specific Document

To retrieve a specific saved object using query criteria ?

db.demo45.findOne({"StudentFirstName": "Chris"});

Key Points

  • Variable access works only within the same MongoDB session
  • Database queries persist across sessions and connections
  • MongoDB automatically adds an _id field when saving objects

Conclusion

You can get saved objects either by accessing the original variable in the same session or by querying the database collection using find() or findOne() methods.

Updated on: 2026-03-15T02:48:49+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements