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

  • $nin ensures the document is only added if the site doesn't already exist in the array.
  • $push adds 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.

Updated on: 2026-03-15T03:42:56+05:30

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements