Mongodb将一个字段作为一个集合数组投影到一个文档中作为结果

时间:2019-04-21 18:58:00

标签: node.js database mongodb mongoose aggregation-framework

这是数据

[ {
            "_id": "5c75802b1312ca10e63d2ca7",
            "external_user_id": "5cbc86081e06c111f9b16fbf"
        },
        {
            "_id": "5c75a35a3cd9af224c0622c1",
            "external_user_id": "5cbc86081e06c111f9b16fbf"
        },
        {
            "_id": "5c82c3bede451c0fd74e6739",
            "external_user_id": "5cbc86081e06c111f9b16fd5"
        },
        {
            "_id": "5c85432c1a515a17f2d7a2e7",
            "external_user_id": "5cbc86081e06c111f9b16fbc"
        },
        {
            "_id": "5c8e8132bfda140998c2f1c4",
            "external_user_id": "5cbc86081e06c111f9b16fbf"
        }]

我希望对mongodb进行类似的查询,根据以下查询将不同的文档字段转换为一个字段数组:

{
external_user_id: ["5cbc86081e06c111f9b16fbc", "5cbc86081e06c111f9b16fbf", "5cbc86081e06c111f9b16fd5"]
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下汇总

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "external_user_id": {
      "$addToSet": "$external_user_id"
    }
  }}
])