MongoDB query to skip first 5 records and display only the last 5 of them

MongoDBDatabaseBig Data Analytics

To skip records in MongoDB, use skip(). With that, to display only a specific number of records, use limit().

Let us create a collection with documents −

> db.demo275.insertOne({"Number":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac4dd099650a5401a43")
}
> db.demo275.insertOne({"Number":12});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac7dd099650a5401a44")
}
> db.demo275.insertOne({"Number":6});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac9dd099650a5401a45")
}
> db.demo275.insertOne({"Number":1});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eacadd099650a5401a46")
}
> db.demo275.insertOne({"Number":5});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eacddd099650a5401a47")
}
> db.demo275.insertOne({"Number":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead0dd099650a5401a48")
}
> db.demo275.insertOne({"Number":8});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead6dd099650a5401a49")
}
> db.demo275.insertOne({"Number":9});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead8dd099650a5401a4a")
}
> db.demo275.insertOne({"Number":19});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eadddd099650a5401a4b")
}
> db.demo275.insertOne({"Number":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eae1dd099650a5401a4c")
}

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

> db.demo275.find();

This will produce the following output −

{ "_id" : ObjectId("5e48eac4dd099650a5401a43"), "Number" : 10 }
{ "_id" : ObjectId("5e48eac7dd099650a5401a44"), "Number" : 12 }
{ "_id" : ObjectId("5e48eac9dd099650a5401a45"), "Number" : 6 }
{ "_id" : ObjectId("5e48eacadd099650a5401a46"), "Number" : 1 }
{ "_id" : ObjectId("5e48eacddd099650a5401a47"), "Number" : 5 }
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }

Following is the query to skip first 5 records and display only the last 5 of them −

> db.demo275.find().skip(5).limit(5)

This will produce the following output −

{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }
raja
Published on 31-Mar-2020 16:41:52
Advertisements