我试图使用mongo聚合获取一组字段中匹配文档的总数。聚合查询就像,
db.results.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}])
那么如何在这里总结所有匹配文件的count
?
一组示例文档就像,
{
"id" : "1",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 697,
"name" : "vendor1"
}
{
"id" : "2",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 380
"name" : "vendor2"
}
{
"id" : "2",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 380,
"name" : "vendor2"
}
{
"id" : "3",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 702,
"name" : "vendor3"
}
{
"id" : "3",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 702,
"name" : "vendor3"
}
UPDATE
遇到toArray()
,所以解决方案似乎是,
db.results.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}],
{allowDiskUse:true}).toArray().length
不,它只给出了匹配集群的数量。
答案 0 :(得分:0)
现在正确地回答你的问题
请参阅此更新的查询,它将为我们提供所需的结果
db.result.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'},
totalAmount:{$sum:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}])
所有计数的总和在totalAmount字段中给出
根据您提供的样本集数据,上面给出的聚合查询的结果是
{
"_id" : {
"name" : "vendor2",
"id" : "2",
"date" : ISODate("2017-04-29T00:00:00Z"),
"amount" : 380
},
"totalAmount" : 760,
"count" : 2
}
{
"_id" : {
"name" : "vendor3",
"id" : "3",
"date" : ISODate("2017-04-29T00:00:00Z"),
"amount" : 702
},
"totalAmount" : 1404,
"count" : 2
}
希望它有帮助!