Tutorialspoint

How to get tag count in MongoDB query results based on list of names?


1 Answer
Nishtha Thakur

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.