Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 tag count in MongoDB query results based on list of names?
You can use $in operator. Let us first create a collection with documents −
> db.tagCountDemo.insertOne({"ListOfNames":["John","Sam","Carol"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd64b387924bb85b3f48944")
}
> db.tagCountDemo.insertOne({"ListOfNames":["Bob","David","John"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd64b4b7924bb85b3f48945")
}
> db.tagCountDemo.insertOne({"ListOfNames":["Mike","Robert","Chris"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd64b5d7924bb85b3f48946")
}
> db.tagCountDemo.insertOne({"ListOfNames":["James","Carol","Jace"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd64b717924bb85b3f48947")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.tagCountDemo.find().pretty();
This will produce the following output −
{
"_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"
]
}
Following is the query to get tag count in MongoDB
> db.tagCountDemo.find({"ListOfNames":{$in:['John','Carol']}});
This will produce the following output −
{ "_id" : ObjectId("5cd64b387924bb85b3f48944"), "ListOfNames" : [ "John", "Sam", "Carol" ] }
{ "_id" : ObjectId("5cd64b4b7924bb85b3f48945"), "ListOfNames" : [ "Bob", "David", "John" ] }
{ "_id" : ObjectId("5cd64b717924bb85b3f48947"), "ListOfNames" : [ "James", "Carol", "Jace" ] }Advertisements