返回MongoDB聚合数据

时间:2017-10-31 22:25:26

标签: node.js mongodb mongoose nosql

我正在使用MongoDB Aggregation来查询两个不同的架构集合。

Artist.aggregate([
    {
        $match: { artistID }
    },
    {
        $lookup: {
            from: "users",
            localField: "userID",
            foreignField: "_id",
            as: "UsersWithMatchedArtist"
        }
    },
    {
        $project: {
            UsersWithMatchedArtist: 1
        }
    }
}
])

这将返回以下数据结构。

[
  {
    "_id": "59f8f40686f2fa623d815256",
    "UsersWithMatchedArtist": [{Users Schema}]
  },
  {
    "_id": "59f8f40686f2f12345678901",
    "UsersWithMatchedArtist": [{Users Schema}}]
  }
]

我希望在以下结构中返回数据

[
  {Users Schema},
  {Users Schema}
]

有关如何执行此操作的任何建议?建议将不胜感激!干杯!

1 个答案:

答案 0 :(得分:0)

要获得理想的结果,可以将$ unwind和$ group添加到现有管道中。

[
    {
        "$match": { artistID }
    },
    {
        "$lookup": {
            "from": "users",
            "localField": "userID",
            "foreignField": "_id",
            "as": "UsersWithMatchedArtist"
        }
    },
    {
        "$project": {
            "UsersWithMatchedArtist": 1
        }
    },
    {
        "$unwind": "$UsersWithMatchedArtist"
    },
    {
        "$group": {
            "_id": null,    // or add your own grouping
            "UsersWithMatchedArtist": {"$push": "$UsersWithMatchedArtist"}
        }
    }
}]

您的输出将采用以下格式:

{
    "_id" : null,
    "users" : [ 
        {Users Schema}, 
        {Users Schema}
    ]
}