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

标签 javascript node.js mongodb mongoose aggregation-framework

我有一些交易数据如下:

[{
  "_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/

相关文章:

node.js - Mongoose 错误 : Cast to embedded failed for value

android - cmd:命令失败,退出代码为 ENOENT

javascript - Node.js 根据其值返回对象键

node.js - 如何将 MongoDB 添加到 Docker 容器?

javascript - 从同一文件中获取 module.exports

node.js - 如何在进行交易时生成客户 ID Braintree

javascript - Mongoose 从集合中获取所有键值并将其放入数组中

javascript - 从本地存储中仅删除选定的列表项 - 纯 JS

javascript - RxJS:Observable.create() 与 Observable.from()

javascript - Array.prototype.map.call 与 Array.map