【问题标题】:MongoDB how to $project (limit fields) from the $lookup remote collection?MongoDB 如何从 $lookup 远程集合中 $project(限制字段)?
【发布时间】:2019-01-05 19:01:33
【问题描述】:

我想 $lookup 查找远程集合,例如 SQL Join,但使用 Mongo。而且我不希望远程文档中的所有键都被拉到源集合中 - 只是一些特定的键。

这是我尝试过的:

[
  {
    $lookup: {
        from: "tables",
        localField: "type",
        foreignField: "_id",
        as: "type"
      }
    },
    {
      $unwind: "$type"
    },
  },
  {
    $project: {
      "type.title": 1
    }
  }
]

但是,这仅打印“type.title”并忽略所有其他键,即使来自原始文档。

有没有办法告诉 MongoDB 只从远程集合中提取特定字段?

【问题讨论】:

    标签: database mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以将以下聚合与 mongodb 3.6 及更高版本一起使用

    [
      { "$lookup": {
        "from": "tables",
        "let": { "type": "$type" },
        "pipeline": [
          { "$addFields": { "owners": { "$cond": { "if": { "$ne": [ { "$type": "$owners" }, "array" ] }, "then": [], "else": "$owners" } } }},
          { "$match": { "$expr": { "$eq": ["$_id", "$$type"] }}},
          { "$project": { "title": 1 }}
        ],
        "as": "type"
      }},
      { "$unwind": "$type" }
    ]
    

    【讨论】:

    • 感谢工作非常好。为了在数组中搜索,我们可以使用$in(除了您提供的内容之外)。
    • 如果我有这个:{ $match: { $expr: { $in: ["$_id", "$$owners"] }}} 并且原始集合中不存在所有者。我有这个错误:MongoError: $in requires an array as a second argument, found: missing你知道我如何设置这个只有所有者存在并且数组中有多个项目吗?
    • 这就是我做到的:$lookup: { from: "users", let: { "owners": "$owners" }, pipeline: [ { $match: { $expr: { $in: ["$$owners", "$_id"] }}}, { $project: { status: 1, personal_info: 1 }} ], as: "owners" } 但不幸的是我无法做到这一点 - 即使在查看了您提供的问题之后。 cond 是否应该作为一个阶段成为管道的一部分?
    • 这简直太完美了。您能否现在将其发布为完整答案,以便其他人可以轻松理解 $project 的完整解决方案?我认为这对其他读者来说会更清楚。
    猜你喜欢
    • 2018-08-06
    • 2018-04-26
    • 1970-01-01
    • 2019-11-08
    • 2019-04-18
    • 2019-05-11
    • 2019-02-25
    • 2017-07-04
    • 2020-09-15
    相关资源
    最近更新 更多