 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"    ] }Advertisements
 