3

Let's say we have this db.orders document collection with one document:

{"_id": "5ef62e0c586c78491530e4d5", "items": [{ "description": "desc1", "parts": ["5ef62e0c586c78491530e4d7", "5ef62e0c586c78491530e4d8"] } ], "createdBy": "userId"}

[CORRECTION: the items field is now an array]

And another db.parts collection with two part documents:

{"_id": "5ef62e0c586c78491530e4d7", "name": "part1" }
{"_id": "5ef62e0c586c78491530e4d8", "name": "part2" }

I would like to construct an aggregation on the first collection replacing the ObjectIds in the parts array with the actual documents. The result should be like:

{"_id": "5ef62e0c586c78491530e4d5", "items": [{ "description": "desc1", "parts":
  [
    {"_id": "5ef62e0c586c78491530e4d7", "name": "part1" },
    {"_id": "5ef62e0c586c78491530e4d8", "name": "part2" }
  ]
}], "createdBy": "userId"}

Any ideas would be much appreciated!

1 Answer 1

1

You need to use the $lookup operator:

db.orders.aggregate([
  {
    $lookup: {
      from: "parts",
      localField: "items.parts",
      foreignField: "_id",
      as: "parts"
    }
  },
  {
    $project: {
      createdBy: 1,
      items: {
        $map: {
          input: "$items",
          as: "item",
          in: {
            description: "$$item.description",
            parts: {
              $filter: {
                input: "$parts",
                as: "part",
                cond: {
                  $in: [ "$$part._id", "$$item.parts" ]
                }
              }
            }
          }
        }
      }
    }
  }
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I actually made a mistake in my question. The "items" field should be an array like: {"_id": "5ef62e0c586c78491530e4d5", "items": [{ "description": "desc1", "parts": ["5ef62e0c586c78491530e4d7", 5ef62e0c586c78491530e4d8] }], "createdBy": "userId"} Doing the lookup it does not preserve the items as an array and I loose the "description" field.
@ThomasSkyttegaardHansen check again please, I've updated my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.