Extract a MongoDB document with a specific string

To extract a MongoDB document with a specific string, use the $match operator in an aggregation pipeline to filter documents containing the target string value.

Syntax

db.collection.aggregate([
    { $match: { "field": "specific_string" } }
]);

Create Sample Data

db.demo424.insertMany([
    {
        "Information": [
            {
                id: 10,
                Name: "Chris"
            },
            {
                id: 11,
                Name: "David"
            }
        ]
    },
    {
        "Information": [
            {
                id: 101,
                Name: "Mike"
            },
            {
                id: 102,
                Name: "John"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display All Documents

db.demo424.find();
{ "_id": ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information": [ { "id": 10, "Name": "Chris" }, { "id": 11, "Name": "David" } ] }
{ "_id": ObjectId("5e74eb9ebbc41e36cc3cae6b"), "Information": [ { "id": 101, "Name": "Mike" }, { "id": 102, "Name": "John" } ] }

Extract Document with Specific String

Find documents where any element in the Information array has Name "Chris" ?

db.demo424.aggregate([
    { $match: { "Information.Name": "Chris" } }
]);
{ "_id": ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information": [ { "id": 10, "Name": "Chris" }, { "id": 11, "Name": "David" } ] }

Alternative Using find()

You can also use the simpler find() method for the same result ?

db.demo424.find({ "Information.Name": "Chris" });

Conclusion

Use $match in aggregation pipelines or find() with dot notation to extract documents containing specific string values in nested arrays. Both methods effectively filter documents based on string matching criteria.

Updated on: 2026-03-15T02:56:11+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements