英文:
how use offset and limit with mongodb?
问题
你好!以下是你要翻译的内容:
如何在Go语言中使用offset和limit与mongodb一起使用?
我需要一个offset来确定我首先获取的API的顺序,我还需要一个limit来指定要显示的API数量。有人曾经做过这样的事吗?
英文:
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?
答案1
得分: 2
你可以使用go.mongodb.org/mongo-driver/mongo
包来实现这个功能。
SetSkip
方法用于指定在返回结果之前要跳过的文档数量(即偏移量)。
SetLimit
方法用于限制结果的数量。
options
是从go.mongodb.org/mongo-driver/mongo/options
导入的。
db.Collection("users").Find(ctx, bson.M{}, options.Find().SetSkip(offset).SetLimit(limit))
英文:
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))
答案2
得分: 0
你可以按照以下方式跳过和限制每个集合中的文档:
db.users.find({}).skip(1).limit(10).sort({_id:1})
你还可以使用mongoose-paginate包来实现这个功能。它还可以提供排序、填充、跳过和限制文档等功能。
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var userSchema = new mongoose.Schema({
name: {
type: String
}
});
userSchema.plugin(mongoosePaginate);
Mongoose paginate接受两个参数作为输入,分别是filter和options。
db.users.paginate(filter, options)
filter是搜索条件,而options具有以下字段:
- select:选择结果中的哪些字段
- sort:按照哪个字段排序以及排序顺序
- populate:如果有ID的引用,则可以进行填充
- lean:是否将结果转换为JavaScript对象
- leanWithId:是否在JavaScript对象中将ObjectId转换为字符串
- offset:要跳过的文档数量
- limit:每页显示的文档数量
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论