top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

MongoDB: How to construct a query in mongoDB when selection of documents have "OR" based condition ?

+1 vote
481 views
MongoDB: How to construct a query in mongoDB when selection of documents have "OR" based condition ?
posted Jun 28, 2015 by Vikram Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

This is a very general query and used day to day basis.
I will explain this by using an example.
A database has a number of collections and a particular collection has documents as following:

{ "_id" : ObjectId("1"), "key1" : 1 }
{ "_id" : ObjectId("2"), "key4" : 1 }
{ "_id" : ObjectId("3"), "key4" : 1 }
{ "_id" : ObjectId("4"), "key4" : 1 }
{ "_id" : ObjectId("5"), "key4" : 1 }
{ "_id" : ObjectId("6"), "key4" : 1 }
{ "_id" : ObjectId("7"), "key4" : 1 }
{ "_id" : ObjectId("8"), "key5" : 1 }

Each row holds data of one document. Now a user want to get the list of documents which have either key1 or key5 fields.
db.secondCollection.find({$or : [{key1:1}, {key5:1}]})

The query constructed above gives the following result.

{ "_id" : ObjectId("1"), "key1" : 1 }
{ "_id" : ObjectId("8"), "key5" : 1 }

I answered your query hope so. If you still have any doubt then please ask.

answer Jun 28, 2015 by Harshita
Harshita, Thanks a lot for your quick response.
Similar Questions
+1 vote

Query description: I have a collection name student_db and added a document in a collection with entries (name: "alok, age : 31 and profession: "xyz"). After inserting the document into student_db database, I want to add another (key:value ) pair i.e. salary: 50000.

Can someone help me out to resolve this problem ?

...