聚合函数不显示计数大于 1 的结果
Aggregate function isn't showing results with a count greater than 1
我是 运行 这个聚合函数,它应该只在计数大于 1 时显示结果。当我删除 'count': { '$gt': 1 }
聚合时,它显然显示了所有结果。我应该如何正确使用这个计数?
db.getCollection('songs').aggregate([
{
'$match': { 'is_song': 1, 'is_soundtrack': 0, 'count': { '$gt': 1 } }
},
{
'$group': { '_id': { 'name': '$name', 'artist_id': '$artist_id' }, 'count': { '$sum': 1 } }
},
{
'$sort': { 'count': -1 }
}
])
示例数据:
{
"_id" : ObjectId("5f93a43b4e8883298849ad18"),
"name" : "Come Fly With Me",
"song_id" : 5,
"artist_id" : 5,
"is_song" : 1,
"is_soundtrack" : 0,
"updatedAt" : ISODate("2016-10-04T13:34:53.328Z")
}
您不应在第一个 $match
阶段添加 'count': { '$gt': 1 }
。
因为 count
字段仅在 $group
阶段之后填充。
因此,您需要在 $group
阶段之后添加另一个 $match
阶段来过滤计数值大于 1 的文档。
db.collection.aggregate([
{
"$match": {
"is_song": 1,
"is_soundtrack": 0
}
},
{
"$group": {
"_id": {
"name": "$name",
"artist_id": "$artist_id"
},
"count": {
"$sum": 1
}
}
},
{
$match: {
"count": {
"$gt": 1
}
}
},
{
"$sort": {
"count": -1
}
}
])
我是 运行 这个聚合函数,它应该只在计数大于 1 时显示结果。当我删除 'count': { '$gt': 1 }
聚合时,它显然显示了所有结果。我应该如何正确使用这个计数?
db.getCollection('songs').aggregate([
{
'$match': { 'is_song': 1, 'is_soundtrack': 0, 'count': { '$gt': 1 } }
},
{
'$group': { '_id': { 'name': '$name', 'artist_id': '$artist_id' }, 'count': { '$sum': 1 } }
},
{
'$sort': { 'count': -1 }
}
])
示例数据:
{
"_id" : ObjectId("5f93a43b4e8883298849ad18"),
"name" : "Come Fly With Me",
"song_id" : 5,
"artist_id" : 5,
"is_song" : 1,
"is_soundtrack" : 0,
"updatedAt" : ISODate("2016-10-04T13:34:53.328Z")
}
您不应在第一个 $match
阶段添加 'count': { '$gt': 1 }
。
因为 count
字段仅在 $group
阶段之后填充。
因此,您需要在 $group
阶段之后添加另一个 $match
阶段来过滤计数值大于 1 的文档。
db.collection.aggregate([
{
"$match": {
"is_song": 1,
"is_soundtrack": 0
}
},
{
"$group": {
"_id": {
"name": "$name",
"artist_id": "$artist_id"
},
"count": {
"$sum": 1
}
}
},
{
$match: {
"count": {
"$gt": 1
}
}
},
{
"$sort": {
"count": -1
}
}
])