MongoDB multiple OR conditions on same key?


For this, simply use $or once. Let us create a collection with documents −

> db.demo551.insertOne({"Name":"John"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e36d39e5f92834d7f05e5")
}
> db.demo551.insertOne({"Name":"Chris Brown"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e36d89e5f92834d7f05e6")
}
> db.demo551.insertOne({"Name":"John Doe"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e36de9e5f92834d7f05e7")
}
> db.demo551.insertOne({"Name":"John Smith"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e36e59e5f92834d7f05e8")
}
> db.demo551.insertOne({"Name":"Carol"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e36ec9e5f92834d7f05e9")
}

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

> db.demo551.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" }
{ "_id" : ObjectId("5e8e36d89e5f92834d7f05e6"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e8e36de9e5f92834d7f05e7"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e8e36e59e5f92834d7f05e8"), "Name" : "John Smith" }
{ "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }

Following is the query to implement OR conditions on the same key −

> db.demo551.find({$or:[
...       {"Name" : {$eq : "Carol"}},
...       {Name: {$eq:"John"}}
...    ]
... });

This will produce the following output −

{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" }
{ "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }

Updated on: 14-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements