MongoDB query for exact match

MongoDBDatabaseBig Data Analytics

For exact match, you can use $exists that checks for a match. Let us create a collection with documents −

> db.demo290.insertOne({"ListOfName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c0c9e5d93261e4bc9ea2d")
}
> db.demo290.insertOne({"ListOfName":["Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c0cb05d93261e4bc9ea2e")
}

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

> db.demo290.find();

This will produce the following output −

{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
{ "_id" : ObjectId("5e4c0cb05d93261e4bc9ea2e"), "ListOfName" : [ "Chris", "David" ] }

Here is the query for exact match of a value −

> db.demo290.find({$and: [{'ListOfName.0': {$exists: false}}, {"ListOfName": 'Chris'}]});

This will produce the following output −

{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
raja
Published on 31-Mar-2020 17:19:55
Advertisements