1
votes

I want to $lookup for a remote collection like SQL Join but with Mongo. And I don't want all of the keys from the remote document to be pulled to the origin collection - just some specific keys.

This is what I have tried:

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

However this prints only "type.title" and ignores all of other keys even from the origin document.

Is there any way to tell MongoDB to pull only specific fields from the remote collection?

1

1 Answers

1
votes

You can use below aggregation with mongodb 3.6 and above

[
  { "$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" }
]