Get at least one match in list querying with MongoDB?

To get at least one match in list querying with MongoDB, use the $in operator. This operator returns documents where the array field contains at least one of the specified values.

Syntax

db.collection.find({
    "arrayField": { "$in": ["value1", "value2", "value3"] }
});

Sample Data

Let us create a collection with sample documents −

db.atleastOneMatchDemo.insertMany([
    {"StudentFavouriteSubject": ["MySQL", "MongoDB"]},
    {"StudentFavouriteSubject": ["Java", "C", "MongoDB"]},
    {"StudentFavouriteSubject": ["Python", "C++", "SQL Server"]},
    {"StudentFavouriteSubject": ["Ruby", "Javascript", "C#", "MySQL"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd2db5db64f4b851c3a13ce"),
        ObjectId("5cd2db71b64f4b851c3a13cf"),
        ObjectId("5cd2db87b64f4b851c3a13d0"),
        ObjectId("5cd2dba9b64f4b851c3a13d1")
    ]
}

Display All Documents

Following is the query to display all documents from the collection −

db.atleastOneMatchDemo.find().pretty();
{
    "_id": ObjectId("5cd2db5db64f4b851c3a13ce"),
    "StudentFavouriteSubject": [
        "MySQL",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd2db71b64f4b851c3a13cf"),
    "StudentFavouriteSubject": [
        "Java",
        "C",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd2db87b64f4b851c3a13d0"),
    "StudentFavouriteSubject": [
        "Python",
        "C++",
        "SQL Server"
    ]
}
{
    "_id": ObjectId("5cd2dba9b64f4b851c3a13d1"),
    "StudentFavouriteSubject": [
        "Ruby",
        "Javascript",
        "C#",
        "MySQL"
    ]
}

Example: Get At Least One Match

Following query finds documents where StudentFavouriteSubject contains at least one of "MongoDB" or "MySQL" −

db.atleastOneMatchDemo.find({
    "StudentFavouriteSubject": { "$in": ["MongoDB", "MySQL"] }
}).pretty();
{
    "_id": ObjectId("5cd2db5db64f4b851c3a13ce"),
    "StudentFavouriteSubject": [
        "MySQL",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd2db71b64f4b851c3a13cf"),
    "StudentFavouriteSubject": [
        "Java",
        "C",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd2dba9b64f4b851c3a13d1"),
    "StudentFavouriteSubject": [
        "Ruby",
        "Javascript",
        "C#",
        "MySQL"
    ]
}

Conclusion

The $in operator efficiently matches documents containing at least one value from the specified array. It returns all documents where the target field has any intersection with the query values.

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

487 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements