gpt4 book ai didi

javascript - 在 $group mongodb 之后获取公共(public)元素

转载 作者:可可西里 更新时间:2023-11-01 09:13:54 28 4
gpt4 key购买 nike

我有一些交易数据如下:

[{
"_id" : ObjectId("5d319aa8df4026532fe5036f"),
"transaction" : ISODate("2018-10-16T04:00:07.000Z"),
"cardnumber" : "1000 0000 0002 0356"
},{
"_id" : ObjectId("5d319aa8df4026532fe5035x"),
"transaction" : ISODate("2018-10-16T04:00:07.000Z"),
"cardnumber" : "1000 0000 0002 0358"
},{
"_id" : ObjectId("5d319aa8df4026532fe5036d"),
"transaction" : ISODate("2018-09-16T04:00:07.000Z"),
"cardnumber" : "1000 0000 0002 0356"
}]

我必须每个月至少获得所有使用过一次的卡号。

所以我的第一个想法是按月和年对它们进行分组:

return transactionsModel.aggregate([{
$group: {
_id: {
year: {
$year: "$transaction"
},
month: {
$month: "$transaction"
}
},
results: {
$push: '$$CURRENT.cardnumber'
}
},

}]).allowDiskUse(true);

该查询的答案是这样的:

[
{
"_id": {
"year": 2018,
"month": 9
},
"results": [
"1000 0000 0002 0356"
]
},
{
"_id": {
"year": 2018,
"month": 10
},
"results": [
"1000 0000 0002 0356",
"1000 0000 0002 0358"
]
}
]

但是之后我不知道如何找到每个组中共有的卡号。

期待回应:

"results": [
"1000 0000 0002 0356"
]

预先感谢您的回答。如果您需要任何其他信息,请询问我会尽力提供。

最佳答案

您可以使用以下聚合

db.collection.aggregate([
{ "$group": {
"_id": {
"year": { "$year": "$transaction" },
"month": { "$month": "$transaction" }
},
"results": { "$push": "$$CURRENT.cardnumber" }
}},
{ "$group": {
"_id": null,
"result": { "$first": "$results" },
"results": { "$push": "$results" }
}},
{ "$project": {
"results": {
"$reduce": {
"input": "$results",
"initialValue": "$result",
"in": { "$setIntersection": ["$$value", "$$this"] }
}
}
}}
])

Output

[
{
"_id": null,
"results": [
"1000 0000 0002 0356"
]
}
]

关于javascript - 在 $group mongodb 之后获取公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132972/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com