我正在運行這個聚合函式,它應該只在計數大于 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")
}
uj5u.com熱心網友回復:
您不應該'count': { '$gt': 1 }在第一$match階段添加。
由于該count欄位僅在$group階段后填充。
因此,您需要在過濾計數值大于 1 的檔案的$match階段后添加另一個階段。$group
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
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417231.html
標籤:
