我需要一个查询来获取基于 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"
}
我需要一个查询来对所有记录进行排序并返回不同的键.....
我需要一个查询来获取基于 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"
}
我需要一个查询来对所有记录进行排序并返回不同的键.....
您可以使用聚合框架按您想要区分的元素进行分组(组使其不同)。因此,如果您希望按分数排序然后获得不同的键,您可以执行以下操作 - 按分数排序,按键分组并将分数添加为元素数组(已排序):
db.test.aggregate([
{ $sort : { score : -1 } },
{ $group : {_id : "$key", scores : { $push : "$score" } } }
])
这将导致不同的键以及分数数组,这些分数是包含在具有重复键的文档中的分数。我不确定这正是您正在寻找的东西,我知道这是一个老问题,但我认为这可能会帮助其他人在未来看到它 - 作为这样做的另一种方式。
mongodb中有不同的命令:
你可以像这样使用 distinct:
db.test.distinct({"key":true,"score":true,"note":true});
在关系数据库中也是如此:
SELECT DISTINCT key,score,note FROM test;
然后通过添加以下代码对结果进行排序:
.sort({score : 1}) // 1 = asc, -1 = desc
总结果将是这样的:
db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1});