MongoDB query for exact match on multiple document fields


For exact match, set the values to be matched inside MongoDB $in(). Let us first create a collection with documents −

> db.demo422.insertOne({"Name":"Chris","Marks":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4059822da45b30346e1")
}
> db.demo422.insertOne({"Name":"Chris","Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a40a9822da45b30346e2")
}
> db.demo422.insertOne({"Name":"David","Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4149822da45b30346e3")
}
> db.demo422.insertOne({"Name":"Sam","Marks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a41e9822da45b30346e4")
}
> db.demo422.insertOne({"Name":"David","Marks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4239822da45b30346e5")
}

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

> db.demo422.find();

This will produce the following output −

{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a40a9822da45b30346e2"), "Name" : "Chris", "Marks" : 56 }
{ "_id" : ObjectId("5e73a4149822da45b30346e3"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e73a41e9822da45b30346e4"), "Name" : "Sam", "Marks" : 45 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }

Following is the query to get records with exact match on multiple document fields −

> db.demo422.find({'$and': [{'Name': {'$in': ['Chris', 'David']}, 'Marks': {'$in': [34,89]}}]});

This will produce the following output −

{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }

Updated on: 03-Apr-2020

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements