Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
_idfield 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.
Advertisements
