MongoDB如何从$ lookup远程集合进行$ project(限制字段)?

时间:2019-01-05 19:01:34

标签: database mongodb mongodb-query aggregation-framework

我想为像SQL Join这样的远程集合加上Mongo进行$ lookup查找。而且我不希望将远程文档中的所有键都拉到原始集合中,而只是某些特定的键。

这是我尝试过的:

sudo service awslogs status
awslogs (pid  25229) is running...

但是,这仅打印“ type.title”,并且甚至忽略了原始文档中的所有其他键。

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

1 个答案:

答案 0 :(得分: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" }
]