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
Querying object's field array values in MongoDB?
To query object's field array values in MongoDB, use the field name directly with the array element value. MongoDB automatically searches within array fields to find documents containing the specified value.
Syntax
db.collection.find({arrayFieldName: "value"});
Sample Data
db.demo295.insertMany([
{"status": ["Active", "Inactive"]},
{"status": ["Yes", "No"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4d4ea65d93261e4bc9ea39"),
ObjectId("5e4d4eb15d93261e4bc9ea3a")
]
}
Display all documents from the collection ?
db.demo295.find().pretty();
{
"_id": ObjectId("5e4d4ea65d93261e4bc9ea39"),
"status": [
"Active",
"Inactive"
]
}
{
"_id": ObjectId("5e4d4eb15d93261e4bc9ea3a"),
"status": [
"Yes",
"No"
]
}
Example
Query documents where the status array contains "Inactive" ?
db.demo295.find({status: "Inactive"});
{ "_id": ObjectId("5e4d4ea65d93261e4bc9ea39"), "status": ["Active", "Inactive"] }
Key Points
- MongoDB automatically searches within array elements when querying array fields.
- Use the field name directly ? no special array syntax needed for basic value matching.
- Returns documents where any element in the array matches the query value.
Conclusion
MongoDB simplifies array querying by allowing direct field-value matching. Simply specify the array field name and target value to find documents containing that element in the array.
Advertisements
