How to find MongoDB documents in a collection with a filter on multiple combined fields?

MongoDBDatabaseBig Data Analytics

You can use $or operator along with find() for this. Let us first create a collection with documents −

> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Robert","IsMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd4fd1e2cba06f46efe9ef1")
}
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Chris","IsMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd4fd322cba06f46efe9ef2")
}
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"David","IsMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd4fd3b2cba06f46efe9ef3")
}
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Carol","IsMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd4fd452cba06f46efe9ef4")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.findDocumentWithFilterDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd4fd1e2cba06f46efe9ef1"),
   "ClientName" : "Robert",
   "IsMarried" : false
}
{
   "_id" : ObjectId("5cd4fd322cba06f46efe9ef2"),
   "ClientName" : "Chris",
   "IsMarried" : true
}
{
   "_id" : ObjectId("5cd4fd3b2cba06f46efe9ef3"),
   "ClientName" : "David",
   "IsMarried" : true
}
{
   "_id" : ObjectId("5cd4fd452cba06f46efe9ef4"),
   "ClientName" : "Carol",
   "IsMarried" : true
}

Following is the query to find documents in a collection with a filter on multiple combined fields −

> db.findDocumentWithFilterDemo.find({  $or: [ { "ClientName": { $ne:"Robert" } }, { "IsMarried": { $ne: false } }  ] } );

This will produce the following output −

{ "_id" : ObjectId("5cd4fd322cba06f46efe9ef2"), "ClientName" : "Chris", "IsMarried" : true }
{ "_id" : ObjectId("5cd4fd3b2cba06f46efe9ef3"), "ClientName" : "David", "IsMarried" : true }
{ "_id" : ObjectId("5cd4fd452cba06f46efe9ef4"), "ClientName" : "Carol", "IsMarried" : true }
raja
Published on 23-May-2019 09:09:09
Advertisements