MongoDB query to skip documents



To skip documents in MongoDB, use skip(). Let us create a collection with documents −

> db.demo263.insertOne({_id:100}); { "acknowledged" : true, "insertedId" : 100 } > db.demo263.insertOne({_id:200}); { "acknowledged" : true, "insertedId" : 200 } > db.demo263.insertOne({_id:300}); { "acknowledged" : true, "insertedId" : 300 }

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

> db.demo263.find();

This will produce the following output −

{ "_id" : 100 } { "_id" : 200 } { "_id" : 300 }

Following is the query to skip document −

> result = db.demo263.aggregate([ ...   { ...      $project: { ...         v_id: { $ifNull: [null, [100, 200]] } ... ...      } ...   }, ...   { $unwind: '$v_id' }, ...   { $sort: { v_id: 1, _id: 1 } }, ... ...   { $skip: 2 }, ...   { $limit: 2 } ...]);

This will produce the following output −

{ "_id" : 300, "v_id" : 100 } { "_id" : 100, "v_id" : 200 }
Updated on: 2020-03-31T08:34:31+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements