【问题标题】:MongoDB Aggregation Data Returned返回的 MongoDB 聚合数据
【发布时间】:2018-04-13 05:05:27
【问题描述】:

我正在使用 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}
]

关于如何做到这一点的任何建议?建议将不胜感激!干杯!

【问题讨论】:

  • 使用$unwind$replaceRoot。或者$project Users Schema 中的每个字段在$unwind 之后,如果你没有$replaceRoot。还是您实际上是在要求“返回所有拥有艺术家条目的用户”? $match 阶段暗示前者而不是后者,但您的问题可能更清楚。
  • 谢谢伙计,$replaceRoot 看起来棒极了!

标签: node.js mongodb mongoose nosql


【解决方案1】:

要获得所需的结果,您可以将 $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}
    ]
}

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多