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
Query an array of embedded documents in MongoDB and push another?
To query an array of embedded documents in MongoDB and push another document, use the $push operator along with update(). You can combine array querying with conditional operations to add new documents only when certain conditions are met.
Syntax
db.collection.update(
{
_id: documentId,
"arrayField.subField": { $nin: ["value"] }
},
{
$push: {
"arrayField": { newDocument }
}
}
);
Sample Data
First, let's create a collection with embedded documents ?
db.demo573.insertOne({
'_id': 101,
'SearchInformation': [
{
'Site': 'Facebook.com',
'NumberOfHits': 100
},
{
'Site': 'Twitter.com',
'NumberOfHits': 300
}
]
});
{ "acknowledged": true, "insertedId": 101 }
Display the initial document ?
db.demo573.find();
{
"_id": 101,
"SearchInformation": [
{ "Site": "Facebook.com", "NumberOfHits": 100 },
{ "Site": "Twitter.com", "NumberOfHits": 300 }
]
}
Query Array and Push New Document
Use $nin (not in) to check if a site doesn't exist, then push a new document ?
db.demo573.update({
_id: 101,
"SearchInformation.Site": {
$nin: ["Google.com"]
}
}, {
$push: {
"SearchInformation": {
'Site': 'Google.com',
'NumberOfHits': 10000
}
}
});
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check the updated document with the new embedded document ?
db.demo573.find().pretty();
{
"_id": 101,
"SearchInformation": [
{
"Site": "Facebook.com",
"NumberOfHits": 100
},
{
"Site": "Twitter.com",
"NumberOfHits": 300
},
{
"Site": "Google.com",
"NumberOfHits": 10000
}
]
}
Key Points
-
$ninensures the document is only added if the site doesn't already exist in the array. -
$pushadds the new document to the end of the SearchInformation array. - Dot notation
"arrayField.subField"allows querying within embedded documents.
Conclusion
Combine array querying with $push to conditionally add embedded documents. Use $nin to prevent duplicates and ensure data integrity when working with arrays of embedded documents.
Advertisements
