简体   繁体   English

MongoDB 聚合 $lookup $match

[英]MongoDB Aggregation $lookup $match

my Connection collection have ObjectId Array field named authors.我的 Connection 集合具有名为 author 的 ObjectId Array 字段。 I want to concat all first names and last names from author arrays.Right now I get name from all users in collection.我想连接作者数组中的所有名字和姓氏。现在我从集合中的所有用户那里得到名字。 Can't get $match aggregation to work.无法让 $match 聚合起作用。 Thank you!谢谢!

Connections Schema连接模式

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

Problem in code代码中的问题

   const connections = await Connection.aggregate([

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

You have authors field in connection schema.您在connection架构中有authors字段。 So instead use authors in let variable to get use in users pipeline { "$in": ["$_id", "$$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"
    }
  }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM