How can I use offset and limit in Go with mongodb?
I need an offset to determine order of APIs I fetch first, and I need a limit to specify number of APIs to display. Has anyone ever made one?
CodePudding user response:
You can use go.mongodb.org/mongo-driver/mongo
package for that.
SetSkip
specifies the number of documents to skip before returning (it is offset).
SetLimit
specifies a limit on the number of results.
options
are imported from go.mongodb.org/mongo-driver/mongo/options
db.Collection("users").Find(ctx, bson.M{}, options.Find().SetSkip(offset).SetLimit(limit))
CodePudding user response:
You can skip and limit the documents per collection as follow
db.users.find({}).skip(1).limit(10).sort({_id:1})
You can also use the mongoose-paginate package for that. It can also provide the feature like sort and populate, along with skip and limit of documents.
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var userSchema = new mongoose.Schema(
{ name:{
type:String
}
});
userSchema.plugin(mongoosePaginate);
Mongoose paginate takes two arguments as input ,which are filter and options
db.users.paginate(filter,options)
filter is the search criteria while options has the following fields:
select: Which fields to select from the result
sort: On which field to sort and in which order
populate :If there is reference of Id then the populate can be done externally.
lean: Should convert the result to js Object or not.
leanWithId: Should also convert ObjectId to string in js Object.
offset: How many documents to skip.
limit: The number of documents per page to be displayed.