问题描述
我在DB中有这样的数据
I have data in DB something like this
[
{ Appname:ktr, softcount:10 ,timeStamp:1 },
{ Appname:rsr, soscount:8,timeStamp:2 },
{ Appname:ktr, softcount:9 ,timeStamp:3},
{ Appname:ssl, softcount:6,timeStamp:4},
{ Appname:ktr, softcount:7,timeStamp:5 },
{ Appname:ppr, softcount:5,timeStamp:6},
{ Appname:crs, softcount:4,timeStamp:7 },
............
]
此处Appname
键将包含未知值.Appname
可能是任何东西.
here Appname
key will contain the value which is unknown value .Appname
might be anything .
我需要根据时间范围找到前5个软计数记录,并且也不应包含相同的Appname
I need to find top 5 softcount record based on the timerange and that too should not contain the same Appname
要找到前5个值,我已使用此查询
To find the top 5 values , I have used this query
db.collection.find({timeStamp : { $gte : startTime, $lte :endTime}}).sort({'softcount':-1}).count(5)
此处startTime为1,endTime为7
here startTime is 1 and endTime is 7
给出前5个softcount
记录,但记录包含相同的Appname
.
it is give top 5 softcount
record but record contains same Appname
. so
我希望从db中获得类似这样的结果
i want the result something like this from db
[
{Appname:ktr,softcount:10,timeStamp:1},
{Appname:rsr,softcount:8,timeStamp:2},
{Appname:ssl,softcount:6,timeStamp:4},
{Appname:ppr,softcount:5,timeStamp:6},
{Appname:crs,softcount:4,timeStamp:7}
]
在此结果中Appnames不同,它不包含相同的Appname
.
in this result Appnames are not same it does not contain the same Appname
.
是否可以编写mongodb查询?
is it possible to write mongodb query ?
要获得以上记录的查询是什么?
what is the query to get above record ?
推荐答案
好,您可以使用聚合管道以想要查看的格式对数据进行分组和投影.
Well, you can use aggregation pipeline to group and project data in format you want to see.
db.col.aggregate([
{$group:{_id:"$Appname", softcount:{$max:"$softcount"}}},
{$project:{_id:0, "Appname":"$_id", softcount:1}},
{$sort:{softcount:-1}},
{$limit: 5}
])
如果输入的内容是您在问题中提到的内容,它将打印以下结果.
this will print following result, provided input is what you mentioned in your question.
{
"softcount" : 10.0,
"Appname" : "ktr"
}
{
"softcount" : 8.0,
"Appname" : "rsr"
}
{
"softcount" : 6.0,
"Appname" : "ssl"
}
{
"softcount" : 5.0,
"Appname" : "ppr"
}
{
"softcount" : 4.0,
"Appname" : "crs"
}
您可以在 https://docs.mongodb.org/manual/上了解有关MongoDB聚合框架的更多信息.聚合/
这篇关于如何在mongodb中找到前5个值?并且不应包含相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!