我的MongoDB数据库中有一堆集合。为了说明我正在尝试弄清楚的东西,这里有一个名为“Restaurant”的示例文档:
{ name: "Foo"
categories: [Pizza, Food]
visits: 10
location: "San Francisco"
}我需要能够查询排名前十的访问过的餐厅,这些餐厅的位置设置为旧金山,按类别中的第一个类别分组。假设所有的集合都有相同的文档格式,那么现在该怎么做呢?
发布于 2012-09-06 05:56:10
首先,您想要查询位置为"San Francisco“的所有文档:
db.foo.find( {location: "San Francisco" } )其次,要找到访问次数最多的餐厅,您需要根据餐厅的访问次数对结果进行排序。您可能希望该列表按访问量的数字顺序相反,因此我们使用访问量:-1:
db.foo.find( {location: "San Francisco"} ).sort( {visits: -1} )为了只获取前10家餐厅,我们将此结果限制为10个结果:
db.foo.find( {location: "San Francisco"} ).sort( {visits: -1} ).limit(10)最后,要获得按类别“分组”的结果,我们可以先按访问量对结果进行排序,然后在该顺序中按类别进行排序:
db.foo.find( {location: "San Francisco"} ).sort( {visits: -1, categories: 1} ).limit(10)https://stackoverflow.com/questions/12290063
复制相似问题