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
Set variable value in MongoDB save() method
To set a variable value in MongoDB's save() method, use db.collectionName.save(variableName) where variableName is your JavaScript variable containing the document data.
Syntax
var variableName = { field1: "value1", field2: "value2" };
db.collectionName.save(variableName);
Example
Let us create a variable with document data and save it to a collection ?
Step 1: Create a Variable
var Info = {
"Name": "David",
"CountryName": "US",
"ProjectDetails": [
{
"ClientName": "David",
"ProjectName": "Online Banking System"
}
]
}
Step 2: Save Variable to Collection
db.demo483.save(Info);
WriteResult({ "nInserted" : 1 })
Step 3: Verify the Document
db.demo483.find().pretty();
{
"_id" : ObjectId("5e82e0d6b0f3fa88e22790a0"),
"Name" : "David",
"CountryName" : "US",
"ProjectDetails" : [
{
"ClientName" : "David",
"ProjectName" : "Online Banking System"
}
]
}
Key Points
- Variables store document data as JavaScript objects before saving to MongoDB.
- The
save()method inserts new documents or updates existing ones based on the_idfield. - MongoDB automatically generates an
_idif not provided in the variable.
Conclusion
Using variables with save() method provides a clean way to store complex document structures in MongoDB. This approach is especially useful for documents with nested arrays and objects.
Advertisements
