How to get documents by tags in MongoDB?


You can use $elemMatch operator for this. Let us create a collection with documents

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

Following is the query to display all documents from a collection with the help of find() method

> db.getDocumentsByTagsDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b79"),
   "Tags" : [
      "Tag-1",
      "Tag-2",
      "Tag-3"
   ]
}
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}
{
   "_id" : ObjectId("5c9eb4d6d628fa4220163b7b"),
   "Tags" : [
      "Tag-6",
      "Tag-4",
      "Tag-3"
   ]
}

Following is the query to get documents by tags

> db.getDocumentsByTagsDemo.find({Tags: { $elemMatch: { $eq: "Tag-2" } }}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b79"),
   "Tags" : [
      "Tag-1",
      "Tag-2",
      "Tag-3"
   ]
}
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}

Following is the query to find specific tags only

> db.getDocumentsByTagsDemo.find({Tags: "Tag-5"}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}

Updated on: 30-Jul-2019

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements