How to query on list field in MongoDB?

To query on list fields in MongoDB, you can use various operators to match array elements, ranges, or specific conditions. MongoDB provides flexible array querying capabilities for finding documents based on array content.

Syntax

// Match exact value in array
db.collection.find({"arrayField": value})

// Match multiple conditions with $or
db.collection.find({"$or": [
    {"arrayField": value1}, 
    {"arrayField": value2}
]})

// Match all specified values with $all
db.collection.find({"arrayField": {"$all": [value1, value2]}})

Sample Data

db.andOrDemo.insertMany([
    {"StudentName": "Larry", "StudentScore": [33, 40, 50, 60, 70]},
    {"StudentName": "Mike", "StudentScore": [87, 67, 79, 98, 90]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9522d316f542d757e2b444"),
        ObjectId("5c95230916f542d757e2b445")
    ]
}

Method 1: Query Single Value in Array

Find documents where the StudentScore array contains the value 70 ?

db.andOrDemo.find({"StudentScore": 70});
{
    "_id": ObjectId("5c9522d316f542d757e2b444"),
    "StudentName": "Larry",
    "StudentScore": [33, 40, 50, 60, 70]
}

Method 2: Query Multiple Values with $or

Find documents where StudentScore contains either 60 or 90 ?

db.andOrDemo.find({
    "$or": [
        {"StudentScore": 60}, 
        {"StudentScore": 90}
    ]
});
{
    "_id": ObjectId("5c9522d316f542d757e2b444"),
    "StudentName": "Larry",
    "StudentScore": [33, 40, 50, 60, 70]
}
{
    "_id": ObjectId("5c95230916f542d757e2b445"),
    "StudentName": "Mike",
    "StudentScore": [87, 67, 79, 98, 90]
}

Method 3: Query with Range Operators

Find students with any score greater than 85 ?

db.andOrDemo.find({"StudentScore": {"$gt": 85}});
{
    "_id": ObjectId("5c95230916f542d757e2b445"),
    "StudentName": "Mike",
    "StudentScore": [87, 67, 79, 98, 90]
}

Key Points

  • Direct field matching automatically searches within array elements
  • $or operator allows matching multiple possible values in arrays
  • Range operators like $gt, $lt work on any array element
  • Use $all to match documents containing all specified values

Conclusion

MongoDB provides powerful array querying capabilities using direct value matching, logical operators like $or, and range operators. These methods enable flexible searching within list fields to find documents based on array content.

Updated on: 2026-03-15T00:22:19+05:30

963 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements