mongodb find query

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We saw how data can be inserted using mongodb insert query. Now we will see how mongodb find query can be used to retrieve data from database.

MongoDB Find Query:

Just like SELECT queries in traditional relational databases, mongodb find query is used for retrieving data from database. If you want to retrieve all documents, you simply write db.collectionName.find();. But what if we want to retrieve the documents based on some query criteria and want to retrieve only some fields?

Mongodb find query has two part, i.e. query and projection. Consider following query.

Now it retrieves the result as below

Let us try to understand by deconstructing this mongodb find query.

find query explained
find query explained 

Note some points.

  • db is a variable which refers to current database being used.
  • employees is the collection on which find query is being fired just like FROM employees in SQL
  • {age:{$gt: 25}} is the query criteria. Just like WHERE age > 25 clause in SQL
  • {name: true, company:1} is the projection part of query. This tells the query to retrieve name and company of documents. Note that true and 1 are both boolean values and have same meaning. It means that name and company fields should be selected and retrieved by the query
  • But in the results you’ve seen _id field also selected, where did it come from? By default mongodb find query always selects _id. So if you want to exclude it, then projection should be {_id:0}.
  • This mongodb find query is equivalent to SELECT _id, name, company FROM Employee WHERE age > 25.

I hope the article helped understand mongodb find query. In further parts, we will see about update operations.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

2 thoughts on “mongodb find query

Leave a Reply

Your email address will not be published. Required fields are marked *