MongoDB 前 3 条记录

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

MongoDB top 3 entries

问题

我想从我的位置表中获取最多的3个访问量最高的条目,并返回它们的ID。我该如何做?我的位置表包含名称、经度、纬度和城市[]。

英文:

I would like to get the most 3 accessed (popular) entries from my Location table and return their ID's. How can I do that?
My Location table contains name,logitude,latitude and city[].

答案1

得分: 1

是的,您需要跟踪文档被获取的次数。您可以使用以下方式实现:

doc = db.foo.findOneAndUpdate({name: 'X'}, {$inc: {count: 1}}, {returnDocument: 'after'});

每次调用 findOneAndUpdate,字段 count 将被递增,并返回整个文档。

要找到前3个最受欢迎的位置,只需使用 sortlimit

db.foo.find().sort({count: -1}).limit(3);
英文:

Yes, you need to track the number of times the document has been fetched. You can do this with:

doc = db.foo.findOneAndUpdate({name:'X'},{$inc: {count:1}}, {returnDocument: 'after'});

Each time you call findOneAndUpdate, the field count will be incremented and the whole doc returned.

To find the top 3 most popular Locations, simply use sort and limit:

db.foo.find().sort({count:-1}).limit(3);

huangapple
  • 本文由 发表于 2023年6月22日 00:54:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525548.html
匿名

发表评论

匿名网友

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

确定