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
MongoDB query to add a document in an already created collection
To add a document to an existing collection in MongoDB, use the $push operator. This operator appends new documents to an existing array field within a document.
Syntax
db.collection.update(
{ "field": "value" },
{ $push: { "arrayField": { newDocument } } }
);
Sample Data
Let's create a collection with sample 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 Current Documents
db.demo177.find().pretty();
{
"_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"]
}
]
}
Example: Adding Document to Array
Following is the query to add a document to the existing details array ?
db.demo177.update(
{ "Id": "101" },
{
$push: {
"details": {
"StudentName": "Bob",
"Scores": [90, 91, 94],
"SubjectName": ["MongoDB", "SQL Server"]
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo177.find().pretty();
{
"_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": "Bob",
"Scores": [90, 91, 94],
"SubjectName": ["MongoDB", "SQL Server"]
}
]
}
Key Points
-
$pushappends the new document to the end of the array field - The update operation modifies the matching document in-place
- Use a proper query filter to target the specific document you want to modify
Conclusion
The $push operator is the primary method to add documents to array fields in existing MongoDB collections. It provides a clean way to append new data without replacing existing array contents.
Advertisements
