How to get tag count in MongoDB query results based on list of names?

To get tag count in MongoDB query results based on a list of names, use the $in operator to match documents containing any of the specified names in an array field, then apply count() to get the total number of matching documents.

Syntax

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

Sample Data

db.tagCountDemo.insertMany([
    {"ListOfNames": ["John", "Sam", "Carol"]},
    {"ListOfNames": ["Bob", "David", "John"]},
    {"ListOfNames": ["Mike", "Robert", "Chris"]},
    {"ListOfNames": ["James", "Carol", "Jace"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd64b387924bb85b3f48944"),
        ObjectId("5cd64b4b7924bb85b3f48945"),
        ObjectId("5cd64b5d7924bb85b3f48946"),
        ObjectId("5cd64b717924bb85b3f48947")
    ]
}

Display All Documents

db.tagCountDemo.find().pretty();
{
    "_id": ObjectId("5cd64b387924bb85b3f48944"),
    "ListOfNames": ["John", "Sam", "Carol"]
}
{
    "_id": ObjectId("5cd64b4b7924bb85b3f48945"),
    "ListOfNames": ["Bob", "David", "John"]
}
{
    "_id": ObjectId("5cd64b5d7924bb85b3f48946"),
    "ListOfNames": ["Mike", "Robert", "Chris"]
}
{
    "_id": ObjectId("5cd64b717924bb85b3f48947"),
    "ListOfNames": ["James", "Carol", "Jace"]
}

Example: Get Tag Count for Specific Names

Find documents containing either "John" or "Carol" in the ListOfNames array ?

db.tagCountDemo.find({"ListOfNames": {$in: ["John", "Carol"]}});
{"_id": ObjectId("5cd64b387924bb85b3f48944"), "ListOfNames": ["John", "Sam", "Carol"]}
{"_id": ObjectId("5cd64b4b7924bb85b3f48945"), "ListOfNames": ["Bob", "David", "John"]}
{"_id": ObjectId("5cd64b717924bb85b3f48947"), "ListOfNames": ["James", "Carol", "Jace"]}

Get the Count

db.tagCountDemo.find({"ListOfNames": {$in: ["John", "Carol"]}}).count();
3

Conclusion

The $in operator efficiently matches documents containing any values from your specified list. Combine it with count() to get the total number of matching documents for tag counting scenarios.

Updated on: 2026-03-15T01:13:55+05:30

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements