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 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
$andoperator 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.
Advertisements
