【问题标题】:MongoDB Aggregation $lookup $matchMongoDB 聚合 $lookup $match
【发布时间】:2020-01-14 22:27:33
【问题描述】:

我的 Connection 集合具有名为 authors 的 ObjectId 数组字段。我想连接作者数组中的所有名字和姓氏。现在我从集合中的所有用户那里得到名字。无法使 $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"
      }
    },

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    connection 架构中有 authors 字段。所以改为在let 变量中使用authors 以在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"
        }
      }
    ])
    

    【讨论】:

    • 谢谢你,就是这样..我现在明白了,但你能告诉我 $expr 是什么意思
    猜你喜欢
    • 2022-07-09
    • 2021-05-04
    • 1970-01-01
    • 2022-01-05
    • 2020-08-07
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多