MongoDB 中是否有类似于 Firestore 中的 .startAfter 选项?

huangapple go评论148阅读模式
英文:

Is there a .startAfter fireStore equivaluent option in MongoDB?

问题

默认情况下,我可以在find()和sort()中使用_id值来跳过文档。但是,我正在使用不同的字段进行排序。因此,文档将根据_id值进行随机排序。

我正在寻找类似于以下内容的东西

db.collection("cities")
.orderBy("population")
.startAfter(lastVisible)
.limit(25);

在mongodb文档中找不到类似的选项。请帮助解决此查询。提前感谢。

英文:

By default, I can use _id value in find() and sort() to skip documents. But, I am sorting using a different field. And hence the documents will be randomly sorted based on _id value.

I am looking for something equivalent of this

db.collection("cities")
                .orderBy("population")
                .startAfter(lastVisible)
                .limit(25);

Couldn't find an equivalent option in mongodb documentation. Kindly help with this query. Thanks in advance.

答案1

得分: 3

在MongoDB中的类似查询如下:

db.collection('cities')
  .find({population: {$gt: lastVisible}})
  .sort({population: 1})
  .limit(25)

当然,实际查询将取决于其他因素,但通常会类似这样。创建一个关于population的索引以确保查询不会成为集合扫描。

参考 $gt创建索引以支持您的查询

注意 1:如果您对MongoDB不熟悉,请查看MongoDB University上的免费课程,以了解更多关于MongoDB的信息。

注意 2不要使用skip+limit进行分页。这是一个已知的反模式。请参考 https://stackoverflow.com/questions/5049992/mongodb-paging使用Bucket模式进行分页 获取更多信息。

英文:

Similar query in MongoDB would be:

db.collection('cities')
  .find({population: {$gt: lastVisible}})
  .sort({population: 1})
  .limit(25)

of course the actual query will depend on other things, but in general it will look like that. Create an index on population to ensure the query won't be a collection scan.

See $gt and Create Indexes to Support Your Queries

Note 1: If you're new to MongoDB, please take a look at free courses in MongoDB University to learn more about MongoDB.

Note 2: Don't use skip+limit for paging. This is a known anti-pattern. See https://stackoverflow.com/questions/5049992/mongodb-paging and
Paging with the Bucket Pattern
for more information.

huangapple
  • 本文由 发表于 2020年1月6日 16:51:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定