Find MongoDB records based on a condition?


To find MongoDB based on a condition, use find() and set the condition. Let us create a collection with documents −

> db.demo708.insertOne({"Name":"John",Marks:54});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702e4d346dcb074dc6f33")
}
> db.demo708.insertOne({"Name":"Chris",Marks:35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702e6d346dcb074dc6f34")
}
> db.demo708.insertOne({"Name":"David",Marks:45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702ebd346dcb074dc6f35")
}
> db.demo708.insertOne({"Name":"Bob",Marks:40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702fad346dcb074dc6f36")
}

Display all documents from a collection with the help of find() method −

> db.demo708.find();

This will produce the following output −

{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 }
{ "_id" : ObjectId("5ea702e6d346dcb074dc6f34"), "Name" : "Chris", "Marks" : 35 }
{ "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }
{ "_id" : ObjectId("5ea702fad346dcb074dc6f36"), "Name" : "Bob", "Marks" : 40 }

Following is the query to find MongoDB records based on a condition −

> db.demo708.find({Marks:{$gt:40}});

This will produce the following output −

{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 }
{ "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }

Updated on: 14-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements