【发布时间】:2020-06-22 18:33:54
【问题描述】:
我第一次使用 MongoDB 聚合结果时遇到了一些麻烦。我正在尝试汇总一些销售总额,但它返回重复的,甚至是三次重复的结果,结果数据相同。有人能弄清楚我做错了什么吗?
这是一个示例数据行:
{
"owner": "Anitta",
"owner_id": ObjectId("5e0e25fc3ed15e27c5f5bb2b"),
"units": NumberInt(19802),
"percent": 0.35,
"value": 30.35063004976345,
"artist_name": "Warner",
"release_title": "Carol",
"upc": "3615937741130",
"track_title": "Carol",
"isrc": "BR9Z21900056",
"store_name": "Spotify",
"country": "Brazil",
"label_name": "Warner Music",
"distributor": "Believe",
"sale_type": "audio",
"sales_id": ObjectId("5e5e91ac238279bd2ba7e839"),
"created_at": ISODate("2020-03-11T20:18:11.076-03:00"),
"report_name": "202002-believe.csv",
"sales_date": ISODate("2019-11-01T21:00:00.000-03:00"),
"distributor_date": ISODate("2020-02-01T00:00:00.000-02:00"),
"distributor_value": 5.355993538193549,
}
这是聚合查询:
filters = { "$match": { owner: { $nin: [false, '', null] } } };
query.push(filters);
query.push({
$group: {
_id: {"owner": "$owner", "owner_id": "$owner_id"},
total_units: { $sum: "$units" },
total: { $sum: "$value" },
}
})
query.push({ $sort: { "total": -1 } })
这是我得到的结果:
{
data: [
{
_id: {
owner: "Anitta",
owner_id: "5e0e25fc3ed15e27c5f5bb2b"
},
total_units: 8127500,
total: 10163.241069212721
},
{
_id: {
owner: "Anitta",
owner_id: "5e0e25fc3ed15e27c5f5bb2b"
},
total_units: 5851785,
total: 2952.923583543785
},
]
}
【问题讨论】:
-
您似乎只提供了部分查询。
-
查询的另一部分只是一个$match。无论如何,我已将其添加到问题中。谢谢!
-
为什么不只在 owner_id 上分组?
-
查询似乎没问题。在 mongo shell 中运行,是否返回预期结果?
-
@CodyGI 使用
owner将其显示在列表中。