Can I get the first item in a Cursor object in MongoDB?


Yes, you can get the first item in a cursor object using findOne() method. Following is the syntax

db.yourCollectionName.findOne();

However, the following syntax is used if you want a single document in a cursor object

db.yourCollectionName.findOne({yourCondition});

We will first create a collection. Following is the query to create a collection with documents

> db.getFirstItemDemo.insertOne({"CustomerName":"Chris","CustomerAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c989059330fd0aa0d2fe4c1")
}
> db.getFirstItemDemo.insertOne({"CustomerName":"Larry","CustomerAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c989063330fd0aa0d2fe4c2")
}
> db.getFirstItemDemo.insertOne({"CustomerName":"Robert","CustomerAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98906d330fd0aa0d2fe4c3")
}
> db.getFirstItemDemo.insertOne({"CustomerName":"David","CustomerAge":39});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c989081330fd0aa0d2fe4c4")
}

Following is the query to display all documents from the collection with the help of find() method

> db.getFirstItemDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c989059330fd0aa0d2fe4c1"),
   "CustomerName" : "Chris",
   "CustomerAge" : 28
}
{
   "_id" : ObjectId("5c989063330fd0aa0d2fe4c2"),
   "CustomerName" : "Larry",
   "CustomerAge" : 26
}
{
   "_id" : ObjectId("5c98906d330fd0aa0d2fe4c3"),
   "CustomerName" : "Robert",
   "CustomerAge" : 29
}
{
   "_id" : ObjectId("5c989081330fd0aa0d2fe4c4"),
   "CustomerName" : "David",
   "CustomerAge" : 39
}

Following is the query to get the first item in a cursor object

> db.getFirstItemDemo.findOne();

This will produce the following output

{
   "_id" : ObjectId("5c989059330fd0aa0d2fe4c1"),
   "CustomerName" : "Chris",
   "CustomerAge" : 28
}

Above, we have the first item in a cursor object. Following is the query to get a single document in a cursor object

> db.getFirstItemDemo.findOne({"CustomerAge":39});

This will produce the following output

{
   "_id" : ObjectId("5c989081330fd0aa0d2fe4c4"),
   "CustomerName" : "David",
   "CustomerAge" : 39
}

Updated on: 30-Jul-2019

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements