Usage of findOne() with MongoDB?

MongoDBDatabaseBig Data Analytics

The findOne() in MongoDB returns only a single document. Let us create a collection with documents −

> db.demo230.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc4d2f4cebbeaebec513e")
}
> db.demo230.insertOne({"FirstName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc4d5f4cebbeaebec513f")
}
> db.demo230.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc4dbf4cebbeaebec5140")
}
> db.demo230.insertOne({"FirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc4dff4cebbeaebec5141")
}
> db.demo230.insertOne({"FirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc4e1f4cebbeaebec5142")
}

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

> db.demo230.find();

This will produce the following output −

{ "_id" : ObjectId("5e3fc4d2f4cebbeaebec513e"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e3fc4d5f4cebbeaebec513f"), "FirstName" : "Bob" }
{ "_id" : ObjectId("5e3fc4dbf4cebbeaebec5140"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e3fc4dff4cebbeaebec5141"), "FirstName" : "David" }
{ "_id" : ObjectId("5e3fc4e1f4cebbeaebec5142"), "FirstName" : "David" }

Following is the query for findOne() in MongoDB −

> db.demo230.findOne({"FirstName":"David"});

This will produce the following output. Returns only one document even if we had more than one document with “FirstName David” −

{ "_id" : ObjectId("5e3fc4dff4cebbeaebec5141"), "FirstName" : "David" }
raja
Published on 30-Mar-2020 13:05:33
Advertisements