如何按数组中符合条件的元素对 MongoDB 结果进行排序?

How to sort MongoDB results by element in array that matches a condition?

我有 collection 个这样的地方 :

{
"_id" : ObjectId("575014da6b028f07bef51d10"),
"name" : "MooD",
.
.
.
"categories" : [
    {
        "categoryList" : [Nightlife, Bar],
        "weight" : 8
    },
    {
        "categoryList" : [Restaurant, Italian Restaurant],
        "weight" : 4
    }
]
}

我想按类别搜索地点,例如 "Bar"。 所以,如果有 "Bar",我会查看类别的 categoryList。 之后,我想按匹配类别权重的权重排序, 这样上面的地方(Bar权重为8)出现在另一个Bar权重为5的地方之前。

你必须使用聚合框架。 检查这个:

db.mongo.aggregate(
    { $unwind: '$scores' },
    { $match: {
        'scores.categoryList': 'Bar'
    }},
    { $sort: {
        'scores.weight': -1
    }}
)