Query in MongoDB

 Use the 

db.collection.find() method in the MongoDB Shell to query documents in a collection.

To return all documents from the sample_mflix.movies collection:

use sample_mflix
db.movies.find()

This operation is equivalent to the following SQL statement:

SELECT * FROM movies

To return all movies where the title equals Titanic from the sample_mflix.movies collection:

use sample_mflix
db.movies.find( { "title": "Titanic" } )

This operation corresponds to the following SQL statement:

SELECT * FROM movies WHERE title = "Titanic"
db.movies.find(query, Projection)




Projection is  used to define a particular thing need to show within a query.


default value for all is none if we set 0 for name then name will not show other field will be show and if we set name : 1 then only name will be shown.

Id is Showing by default so we can set id: 0 if we don't want to show _id.


if we want to set limit or want only one result or limited result then.

db.movies.find(query, Projection).pretty().limit(1)

This method will set an limit to data.

Another Method to Set Limit is:

db.movies.findOne(query, projection) --pretty method will not work in this case

Offset in MongoDB

skip(number)

db.movie.find(query, projection).pretty().limit(1).skip(1)

this will after 1 document match with query.


Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form