我的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"
      }
    },

最佳答案

您在authors模式中具有connection字段。因此,请在authors变量中使用let来在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"
    }
  }
])

关于javascript - MongoDB聚合$ lookup $ match,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59735482/

10-16 20:00