How to get documents by tags in MongoDB?

To find documents by tags in MongoDB, you can use the $elemMatch operator or simple array matching. MongoDB provides several ways to query documents containing specific tags in array fields.

Syntax

// Using $elemMatch operator
db.collection.find({Tags: { $elemMatch: { $eq: "tagValue" } }});

// Simple array matching
db.collection.find({Tags: "tagValue"});

// Multiple tags using $in
db.collection.find({Tags: { $in: ["tag1", "tag2"] }});

Sample Data

db.getDocumentsByTagsDemo.insertMany([
    {"Tags": ["Tag-1", "Tag-2", "Tag-3"]},
    {"Tags": ["Tag-2", "Tag-4", "Tag-5"]},
    {"Tags": ["Tag-6", "Tag-4", "Tag-3"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9eb4d5d628fa4220163b79"),
        ObjectId("5c9eb4d5d628fa4220163b7a"),
        ObjectId("5c9eb4d6d628fa4220163b7b")
    ]
}

Method 1: Using $elemMatch

Find documents containing "Tag-2" ?

db.getDocumentsByTagsDemo.find({Tags: { $elemMatch: { $eq: "Tag-2" } }});
{
    "_id": ObjectId("5c9eb4d5d628fa4220163b79"),
    "Tags": ["Tag-1", "Tag-2", "Tag-3"]
}
{
    "_id": ObjectId("5c9eb4d5d628fa4220163b7a"),
    "Tags": ["Tag-2", "Tag-4", "Tag-5"]
}

Method 2: Simple Array Matching

Find documents containing "Tag-5" using direct array matching ?

db.getDocumentsByTagsDemo.find({Tags: "Tag-5"});
{
    "_id": ObjectId("5c9eb4d5d628fa4220163b7a"),
    "Tags": ["Tag-2", "Tag-4", "Tag-5"]
}

Method 3: Multiple Tags with $in

Find documents containing either "Tag-1" or "Tag-6" ?

db.getDocumentsByTagsDemo.find({Tags: { $in: ["Tag-1", "Tag-6"] }});
{
    "_id": ObjectId("5c9eb4d5d628fa4220163b79"),
    "Tags": ["Tag-1", "Tag-2", "Tag-3"]
}
{
    "_id": ObjectId("5c9eb4d6d628fa4220163b7b"),
    "Tags": ["Tag-6", "Tag-4", "Tag-3"]
}

Key Points

  • $elemMatch is useful for complex conditions within array elements.
  • Simple array matching (Tags: "value") is the most efficient for exact matches.
  • $in operator helps find documents matching any of the specified tags.

Conclusion

Use simple array matching for basic tag searches, $elemMatch for complex conditions, and $in for multiple tag queries. Simple matching is generally the most efficient approach for tag-based document retrieval.

Updated on: 2026-03-15T00:39:58+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements