MongoDB聚合$ lookup $ match

乌罗斯·卡拉伊季奇(Uros Kalajdzic)

我的Connection集合具有名为authors的ObjectId Array字段。我想合并作者数组中的所有名字和姓氏。现在,我从集合中的所有用户那里获取名字。无法使$ match聚合起作用。谢谢!

连接架构

const connectionSchema = new mongoose.Schema({
  authors: [{ type: mongoose.Schema.Types.ObjectId, required: true }],
  messages: [messageSchema]
});

代码问题

   const connections = await Connection.aggregate([

    {
      $lookup: {
        from: "users",
        let: { users: "users" },
        pipeline: [
          { $match: { _id: { $in: ["_id", "$authors"] } } },
          {
            $project: {
              name: {
                $concat: ["$firstname", " ", "$lastname"]
              }
            }
          }
        ],
        as: "userName"
      }
    },
阿什

authorsconnection架构中字段因此,使用authorsinlet变量即可在users管道中使用{ "$in": ["$_id", "$$authors"] }

const connections = await Connection.aggregate([
  {
    "$lookup": {
      "from": "users",
      "let": { "authors": "$authors" },
      "pipeline": [
        { "$match": { "$expr": { "$in": ["$_id", "$$authors"] } } },
        {
          "$project": {
            "name": {
              "$concat": ["$firstname", " ", "$lastname"]
            }
          }
        }
      ],
      "as": "userName"
    }
  }
])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章