通过排序数据获得不同的值

问题描述 投票:14回答:2

我需要一个Query来获取不同的密钥,并根据Mongodb 1.6.5中的分数进行排序

我有唱片喜欢

{key ="SAGAR"
score =16
note ="test1"
}

{key ="VARPE"
score =17
note ="test1"
}

{key ="SAGAR"
score =16
note ="test2"
}

{key ="VARPE"
score =17
note ="test2"
}

我需要一个查询,对得分上的所有记录进行排序,并返回给我不同的密钥......

sorting mongodb distinct-values
2个回答
3
投票

mongodb中有distinct command

你可以像这样使用distinct:

db.test.distinct({"key":true,"score":true,"note":true}); 

关系数据库中相同:

SELECT DISTINCT key,score,note FROM test; 

而且比sort result添加以下代码:

.sort({score : 1}) // 1 = asc, -1 = desc

总结果将是这样的:

 db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1}); 

11
投票

您可以使用聚合框架按要分离的元素进行分组(组使其不同)。因此,如果您希望对分数进行排序,则可以获得不同的密钥,您可以执行以下操作 - 按分数排序,按键分组并将分数添加为元素数组(已排序):

db.test.aggregate([
    { $sort : { score : -1 } },
    { $group : {_id : "$key", scores : { $push : "$score" } } }
])

这将导致不同的键以及分数数组,这些分数是包含在具有重复键的文档中的那些分数。我不确定这正是你正在寻找的东西,我知道这是一个古老的问题,但我认为这可能有助于将来看待它的其他人 - 作为另一种方式。

© www.soinside.com 2019 - 2024. All rights reserved.