MongoDB query to get array of nested string?

To get array of nested string in MongoDB, use dot notation in find() to query nested array fields. This allows you to search for documents containing specific string values within nested arrays.

Syntax

db.collection.find({ "parentArray.nestedField": "searchValue" });

Sample Data

db.demo89.insertMany([
    {
        id: 101,
        Details: [
            { Name: "Chris", Marks: 45 },
            { Name: "David", Marks: 55, Subjects: ["MySQL", "MongoDB", "Java", "C"] }
        ]
    },
    {
        id: 102,
        Details: [
            { Name: "Mike", Marks: 48 },
            { Name: "Bob", Marks: 98, Subjects: ["C++", "MySQL"] }
        ]
    }
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5e2c163b79799acab037af51"),
        ObjectId("5e2c163c79799acab037af52")
    ]
}

Display All Documents

db.demo89.find();
{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }
{ "_id" : ObjectId("5e2c163c79799acab037af52"), "id" : 102, "Details" : [ { "Name" : "Mike", "Marks" : 48 }, { "Name" : "Bob", "Marks" : 98, "Subjects" : [ "C++", "MySQL" ] } ] }

Query Nested String Array

Find documents where the nested Subjects array contains "MongoDB" ?

db.demo89.find({ "Details.Subjects": "MongoDB" });
{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }

Key Points

  • Use dot notation to access nested array fields: "parentArray.nestedField"
  • MongoDB automatically searches all elements in the nested array for the specified value
  • Returns the entire document when a match is found in any nested array element

Conclusion

Use dot notation with find() to query nested string arrays in MongoDB. The format "Details.Subjects": "value" searches for the specified string within nested arrays and returns matching documents.

Updated on: 2026-03-15T01:53:05+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements