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
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
-
$elemMatchis useful for complex conditions within array elements. - Simple array matching (Tags: "value") is the most efficient for exact matches.
-
$inoperator 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.
Advertisements
