How to return the position of a document relative to the collection in MongoDB?


To return the position of a document relative to the collection, use sort() along with count(). Let us create a collection with documents −

> db.demo47.insertOne({"ClientName":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e267240cfb11e5c34d898f0")
}
> db.demo47.insertOne({"ClientName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e267243cfb11e5c34d898f1")
}
> db.demo47.insertOne({"ClientName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e267247cfb11e5c34d898f2")
}
> db.demo47.insertOne({"ClientName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e26724ccfb11e5c34d898f3")
}

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

> db.demo47.find();

This will produce the following output −

{ "_id" : ObjectId("5e267240cfb11e5c34d898f0"), "ClientName" : "Adam" }
{ "_id" : ObjectId("5e267243cfb11e5c34d898f1"), "ClientName" : "John" }
{ "_id" : ObjectId("5e267247cfb11e5c34d898f2"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5e26724ccfb11e5c34d898f3"), "ClientName" : "Sam" }

Following is the query to return the position of a document relative to the collection in MongoDB −

> db.demo47.find({ClientName: {$lt: "John"}}).sort({ClientName: 1}).count();

This will produce the following output −

2

Updated on: 03-Apr-2020

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements