MongoDb Tutorial

Day 6 : Query document in MongoDB








Mongodb tutorial series

Overview

In this part of the Learn Mongo Series, we will learn how to query a document in mongodb.

find() method of mongodb


find() method in mongodb is used to query the documents from collections. Syntax is db.collection_name.find() . Examples are given below :

  • Display all documents : db.collection_name.find() method is used to print all the documents on the console as shown below :

    											
    > use students
    switched to db students
    > db.details.find()
    { "_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"), "name" : "nodejsera", "age" : "10", "description" : "Mongodb tuttorial series" }
    { "_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"), "name" : "a", "age" : "11", "description" : "learn mongodb" }
    { "_id" : ObjectId("5996be4fa4b26dc0d6d75c1e"), "name" : "b", "age" : "12", "description" : "something " }
    >								
    
    									
    											
    										

  • Display documents matching a certain criteria : db.collection_name.find({search_criteria}) method is used to print all the documents on the console as shown below :

    											
    > use students
    switched to db students
    > db.details.find({"name": "nodejsera"})
    { "_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"), "name" : "nodejsera", "age" : "10", "description" : "Mongodb tuttorial series" }
    >								
    
    									
    											
    										


RDBMS where clause equivalents in mongodb


Operation Syntax Example
Equality {:} db.demo_collection.find({"name":"sophia"})
Less than {:{$lt:}} db.demo_collection.find({"age":{$lt:24}})
greater than {:{$gt:}} db.demo_collection.find({"age":{$gt:22}})
not equals {:{$ne:}} db.demo_collection.find({"age":{$ne:25}})
Less than equals {:{$lte:}} db.demo_collection.find({"age":{$lte:24}})
greater than equals {:{$gte:}} db.demo_collection.find({"age":{$gte:22}})

Summary

In this part of learn mongo series , we learned about how we can query documents from mongodb collection. We learned the following commands of mongodb :

  1. use : This command is use to either create a new database or switch to an already existing database.
  2. db.Collection_name.find() : This command is used to display all the documents in the mongodb collection.
  3. db.details.find({search_criteria}) : This command is used to display all the documents in the mongodb collection which matches the search_criteria .