MongoDB按每个组进行排序和限制的分组

17 浏览
0 Comments

MongoDB按每个组进行排序和限制的分组

例如,我有一个集合:

{ "_id" : 1, "name" : "abc", "score" : 10 }
{ "_id" : 2, "name" : "abc", "score" : 15 }
{ "_id" : 3, "name" : "abc", "score" : 20 }
{ "_id" : 4, "name" : "xyz", "score" : 10 }
{ "_id" : 5, "name" : "xyz", "score" : 15 }
{ "_id" : 6, "name" : "xyz", "score" : 20 }

我应该如何在Mongodb中进行查询,按name进行分组,然后按score进行排序,并使用limit=2进行限制。我想要得到如下结果:

{"_id": "abc", "items": [

{ "_id" : 3, "name" : "abc", "score" : 20 },

{ "_id" : 2, "name" : "abc", "score" : 15 }]

}

{"_id": "xyz", "items": [

{ "_id" : 6, "name" : "xyz", "score" : 20 },

{ "_id" : 5, "name" : "xyz", "score" : 15 }]

}

0
0 Comments

MongoDB中的group by操作可以使用aggregate方法来实现。然而,在进行group操作时,MongoDB无法保证之前的排序被group操作保留下来,尤其是在处理大数据集或分片集群时,排序的顺序可能会被打乱。目前,还没有一种直接的方法可以解决这个问题。

一个解决方法是在group操作之前先进行排序,然后再进行group操作。这样可以确保group操作按照预期的顺序进行,并且在每个group中加上限制条件。下面是一个示例代码:

db.collection.aggregate([
    {$sort:{name:-1, score:-1}},
    {$group:{_id:"$name",items:{$push:{score:"$score"}}}}, 
    {$project:{items:{$slice:["$items", 2]}}}
]);

上述代码首先对集合进行排序,然后根据"name"字段进行group操作,并将每个group的"score"字段组成一个数组。最后,使用$project操作将每个group中的数组截取前两个元素作为结果返回。

这样可以确保每个group内的排序顺序被保留,并且限制每个group只返回前两个元素。

然而,需要注意的是,即使使用了排序和限制条件,MongoDB也无法保证在处理大数据集或分片集群时结果的顺序完全一致。因此,在实际使用中,还需要根据具体情况来考虑是否需要进一步处理结果的顺序。

希望以上解决方法能对你有所帮助。如果你还有其他问题,请随时向我提问。

0