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 }