Query Array for 'true' value at index n in MongoDB?

To query an array for a true value at a specific index in MongoDB, use dot notation with the array field name followed by the index position. This allows you to check boolean values at exact array positions.

Syntax

db.collection.find({"arrayField.INDEX": true});

// Multiple index conditions
db.collection.find({
    $and: [
        {"arrayField.INDEX1": true},
        {"arrayField.INDEX2": true}
    ]
});

Sample Data

db.containsTrueValueDemo.insertOne({
    "IsMarried": [true, false, true, true, true, true, false, true, false, false, true]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd5039c2cba06f46efe9ef5")
}

Display the document to verify the data ?

db.containsTrueValueDemo.find().pretty();
{
    "_id": ObjectId("5cd5039c2cba06f46efe9ef5"),
    "IsMarried": [
        true,
        false,
        true,
        true,
        true,
        true,
        false,
        true,
        false,
        false,
        true
    ]
}

Example 1: Query for True at Index 2

Find documents where the value at index 2 is true ?

db.containsTrueValueDemo.find({"IsMarried.2": true});
{
    "_id": ObjectId("5cd5039c2cba06f46efe9ef5"),
    "IsMarried": [true, false, true, true, true, true, false, true, false, false, true]
}

Example 2: Query Multiple Index Positions

Find documents where both index 0 and index 2 have true values ?

db.containsTrueValueDemo.find({
    $and: [
        {"IsMarried.0": true},
        {"IsMarried.2": true}
    ]
});
{
    "_id": ObjectId("5cd5039c2cba06f46efe9ef5"),
    "IsMarried": [true, false, true, true, true, true, false, true, false, false, true]
}

Key Points

  • Array indexing starts from 0 (first element is index 0).
  • Use $and operator to combine multiple index conditions.
  • This method works for any data type, not just boolean values.

Conclusion

Use dot notation with array index positions to query specific elements in MongoDB arrays. Combine multiple conditions with $and for precise array element matching at multiple positions.

Updated on: 2026-03-15T01:12:09+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements