Last Updated:

MongoDB :  Find data

MongoDB
 
Search for information in a MongoDB database.


To search the Mongo DB database, use the find() method.

Suppose we have a "posts" database with publications (Supplement the database with your values based on the example in MongoDB article: Adding Data).

Once the database is filled with data.
Let's search for publications that have a rating of 20:

As a result, all publications with a rating of 20 will be returned to you:
 
db.posts.find({rate: 20}, {})
 

Now let's search for several parameters (rate and title).

We will find all publications with a rating of 20 and the heading "Publication Title".

The result of this query:
 db.posts.find({rate: 20, title: "Post title"}, {})
 

Displays the required fields.

 


Let's say we understand a situation in which we need to get a publication that has a rating of 20 and the title "Title of the publication", but we do not need all the fields, but only the value of the title and description fields.

In this case, the query will look like this:

As a result, we get a record with the required rating, title and get only the values of the title and description fields.
db.posts.find({rate: 20, title: "Post Title"}, {title: 1, description: 1}

As you can see, as a result of the query, we also received the value of the _id field.
In order to exclude the values of the _id field, you must pass the _id key with a value of 0.

Now we have the same record with title, description values, but without the value of the _id field.
db.posts.find({rate: 20, title: "Post Title"}, {title: 1, description: 1, _id: 0})
 

Search for data by ID:

To search an object in the database by ID, you need to run a query:

Where 5e21c56b9891f84be6e23550 is the identifier of your object.
Result:
db.posts.find({_id: ObjectId("5e21c56b9891f84be6e23550")}, {})
 

Condition queries


  • $lt is less
  • $lte is less than or equal to
  • $gt = more
  • $gte is greater than or equal to
  • $ne is not equal

Select all publications that have a rating greater than or equal to 20:

Result:
 db.posts.find({rate: {$gte: 20}}, {})
 

Select all publications with a rating greater than or equal to 20 or less than or equal to 30:

Result:
db.posts.find({rate: {$gte: 20, $lte: 30}}, {})
 

Output of publications whose rating is not equal to 20:

Result:
db.posts.find({rate: {$ne: 20}}, {})
 

Output of publications whose rating is 44 and 30:

Result:
db.posts.find({rate: { $in: [44, 30] }}, {})