【发布时间】:2014-02-10 03:47:14
【问题描述】:
假设我在 MongoDB 中有一个 users 集合。典型的用户文档包含一个名称字段和一组子文档,代表用户的特征。说这样的话:
{
"name": "Joey",
"characteristics": [
{
"name": "shy",
"score": 0.8
},
{
"name": "funny",
"score": 0.6
},
{
"name": "loving",
"score": 0.01
}
]
}
我怎样才能找到前 X 个最有趣的用户,按他们的有趣程度排序?
到目前为止,我发现的唯一方法是在类似于以下的查询中使用聚合框架:
db.users.aggregate([
{$project: {"_id": 1, "name": 1, "characteristics": 1, "_characteristics": '$characteristics'}},
{$unwind: "$_characteristics"},
{$match: {"_characteristics.name": "funny"}},
{$sort: {"_characteristics.score": -1}},
{$limit: 10}
]);
这似乎正是我想要的,除了根据MongoDB's documentation on using indexes in pipelines,一旦我在聚合管道中调用$project 或$unwind,我就不能再利用索引来匹配或排序集合,这使得该解决方案对于非常大的集合有些不可行。
【问题讨论】: