Find document from collection where field(column) EXISTS or not in collection in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >

Find document from collection where field(column) EXISTS or not in collection in MongoDB >

First, Let's create new collection and insert document in it >
> db.employee.insert({_id : 1,  firstName:"ankit"})
> db.employee.insert({_id : 2,  firstName:"ankit", salary : 1000 })
> db.employee.insert({_id : 3,  firstName:"sam", salary : 2000 })
> db.employee.insert({_id : 4,  firstName:"neh", salary : 3000 })
First line above will create table (or collection) (if table already exists it will insert documents in it).


1) FIND Example > find document from collection where field(column) salary exists >


Now, let's display document of collection where field(column) salary exists >
> db.employee.find({salary:{$exists : true}})
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }
{ "_id" : 4, "firstName" : "neh", "salary" : 3000 }


So, you will see that only newly inserted document which contains column salary was displayed.

2) Now, let's display documents of collection where field salary DOESN'T exists >
> db.employee.find({ salary : {$exists : false}})
Output>
{ "_id" : 1, "firstName" : "ankit" }


So, you will see that newly inserted document which contains column salary was NOT displayed.




3) SUMMARY>
So in this mongoDB tutorial we learned how to Find document from collection where field(column) EXISTS or not in collection in MongoDB.


1) FIND Example > find document from collection where field(column) salary exists >
> db.employee.find({salary:{$exists : true}})

2) Now, let's display documents of collection where field salary DOESN'T exists >
> db.employee.find({ salary : {$exists : false}})

Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :