Some handy MONGO DB query operators !

mongodb
MongoDB is an open-source document database and leading NoSQL database. It stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time. It is one of it’s best attribute on why it is so popular nowadays among developers.
Example schema which we will use for our example. We will mainly deal with find query in this section.

So, in this blog i will highlight some of it’s find operators which I find quite useful.

1.) ‘$exists’ :- Let’s say in the above schema we have to search doc in which a particular key exists or not. For example, if we want to identify which doc is not having ‘city’ key we can use this operator.
Query : db.collection.find( { ‘ city ‘: { ‘$exists’ : false } } )
Desc : it will return the doc which do not have this key.
2.) ‘$in’ :-  The $in operator selects the documents where the value of a field equals any value in the specified array. Let’s say we want to select all those docs where city is either jaipur or delhi. So, in that case we can use this operator this way :
Querydb.collection.find( { ‘ city ‘: { ‘$in’ : [‘jaipur’,’delhi’] } } )

3.) ‘$nin’ :- $nin selects the documents where the field value is not in the specified array or the field does not exist. Let’s say we want to select all those docs where city is not jaipur as well as delhi. This operator comes handy in this case.
Querydb.collection.find( { ‘ city ‘: { ‘$nin’ : [‘jaipur’,’delhi’] } } )
Desc. : It will return third & fourth doc as there is no key named city in third and city is gurugram in fourth doc.

Hope the above info helps you in your hacking.
Keep rocking 🙂

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.