【发布时间】:2020-05-27 19:17:23
【问题描述】:
以下是我的样本集:-
{
"_id" : "fffdb22b-912d-4166-909b-7d0fe790ba2a",
"companyVendorId" : "1001",
"date" : ISODate("2019-01-02T05:30:00.000+05:30"),
"amount" : 100
},
{
"_id" : "fff94874-27af-4a39-ae59-3a46b8c7f573",
"companyVendorId" : "1002",
"date" : ISODate("2019-01-25T05:30:00.000+05:30"),
"amount" : 200
},
{
"_id" : "fff94874-27af-4a39-ae59-3a46b8c7f573",
"companyVendorId" : "1002",
"date" : ISODate("2019-01-29T05:30:00.000+05:30"),
"amount" : 200
},
{
"_id" : "fff68faf-2f11-480f-83d2-bfcb45b12d5b",
"companyVendorId" : "1004",
"date" : ISODate("2019-01-12T05:30:00.000+05:30"),
"amount" : 500
},
{
"_id" : "fff4dfaa-46cd-48e3-a871-1f086a2c5438",
"companyVendorId" : "1005",
"date" : ISODate("2019-02-13T05:30:00.000+05:30"),
"amount" :600
},
{
"_id" : "fff18ff2-015e-4ddc-81f2-a12ab3503d05",
"companyVendorId" : "1006",
"date" : ISODate("2019-02-08T05:30:00.000+05:30"),
"amount" : 700
},
{
"_id" : "ffeb16cd-ae1b-4c1e-aa93-d64347b5ff38",
"companyVendorId" : "1007",
"date" : ISODate("2019-02-18T05:30:00.000+05:30"),
"amount" :800
}
要求 :- 我需要每个月(本年度)的前 2 个供应商,根据他们的数量,如果一个月内有多个相同的“companyVendorId”交易,那么我们需要显示金额总和。
预期结果:-
{
"month":1
"companyVendorId" : "1004",
"totalAmount" : 500
},
{
"month":1
"companyVendorId" : "1002",
"totalAmount" : 400
},
{
"month":2
"companyVendorId" : "1007",
"totalAmount" :800
},
{
"month":2
"companyVendorId" : "1006",
"totalAmount" : 700
}
到目前为止,我正处于尝试进行查询之间,下面的查询我能够进行:-
db.getCollection('transaction').aggregate([
{
"$project":
{
"amount": 1,
"companyVendorId":1,
"month": { "$month": "$date" }, "year": { "$year": "$date" }
}
},
{
"$match":
{
"year": 2020
}
}, {
"$group": {
"_id": {
"month": "$month",
"companyVendorId":"$companyVendorId"
},
"totalAmount": { "$sum": "$amount" }
}
}
])
此查询根据我的要求给出结果,但无法选择前 2 名供应商。
【问题讨论】:
-
请包含与您的输入相匹配的预期输出
-
如果同一个 companyVendorId 的总和大于 top
companyVendorId会发生什么?示例:companyVendorId" : "1002", "totalAmount" : 501 -
@Valijon 所以在这种情况下 companyVendorId" : "1002" 记录将首先出现。
-
@thammada 我不确定你在问什么,我已经在我的问题中添加了预期的输出,并且它也与输入匹配,在预期的输出“月”字段中显示该记录用于哪个月份和“companyVendorId”已经在我的集合中,并且“totalAmount”字段指定了“amount”字段的总数。所以就我而言,我的问题是正确的。
-
@HarishBagora 抱歉,我错过了那部分。我可能以某种方式滚动过去。并认为这是输入。
标签: mongodb aggregation-framework