MongoDB query to find matching documents given an array with values?


For specific documents, use MongoDB $in. Let us create a collection with documents −

> db.demo511.insertOne({"ListOfProject":["Library Management System","Hospital
Management System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88473a987b6e0e9d18f585")
}
> db.demo511.insertOne({"ListOfProject":["Online Web Tracking","Library Management
System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884751987b6e0e9d18f586")
}
> db.demo511.insertOne({"ListOfProject":["Online Shopping Cart","Hospital Management
System"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884776987b6e0e9d18f587")
}

Display all documents from a collection with the help of find() method −

> db.demo511.find();

This will produce the following output −

{ "_id" : ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject" : [ "Library Management
System", "Hospital Management System" ] }
{ "_id" : ObjectId("5e884751987b6e0e9d18f586"), "ListOfProject" : [ "Online Web Tracking",
"Library Management System" ] }
{ "_id" : ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject" : [ "Online Shopping Cart",
"Hospital Management System" ] }

Following is the query to finding matching documents −

> db.demo511.find({ "ListOfProject":{$in:["Hospital Management System","Online Shopping Cart"]}});

This will produce the following output −

{ "_id" : ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject" : [ "Library Management
System", "Hospital Management System" ] }
{ "_id" : ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject" : [ "Online Shopping Cart",
"Hospital Management System" ] }

Updated on: 13-May-2020

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements