【问题标题】:Return this dataset as an array of user schema objects in mongoDB将此数据集作为 mongoDB 中的用户模式对象数组返回
【发布时间】:2018-04-14 06:14:48
【问题描述】:

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

我要做的是返回已添加到每个艺术家收藏中的所有用户。

这是艺术家架构

{
"_id" : ObjectId("59f7a13163241a5c8a580832"),
"artistID" : "34657839393",
"artistName" : "Mc squared",
"userID" : ObjectId("599f14855e9fcf95d0fe11a7"),
"__v" : 0

}

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}
]

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

【问题讨论】:

    标签: json node.js mongodb mongoose nosql


    【解决方案1】:

    我得到了使用以下查询后的数据集:

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

    这会返回数据集

    [
      {Users Schema},
      {Users Schema}
    ]
    

    【讨论】:

      猜你喜欢
      • 2021-10-23
      • 2014-05-20
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2012-01-02
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多