0

Let's say I have the following document structure:

{
  "A": {
    "_id": "ID0"
  },
  "B": [
    {
      "_id": "ID0",
      "field": "X"
    },
    {
      "_id": "ID1",
      "field": "Y"
    }
  ]
}

I want to project B matched with the _id in A. The end result would be:

{
  "B": [
    {
      "_id": "ID0",
      "field": "X"
    }
  ]
}

I tried the following but apparently I'm doing something wrong. Is it possible to match based on a document filed rather than an explicit condition?

db.collection.aggregate([
  {$match: {"B._id": "$A._id"}},
  {$project: {"B": 1}}
])
10
  • your document structure is not a valid json... Commented Apr 15, 2020 at 9:29
  • I just made up that example so I might have missed a character somewhere. Feel free to point it out! Commented Apr 15, 2020 at 9:32
  • B is an array... 'a' and 'b' are fields of same object? two different objects? Not a typo, but a structure issue Commented Apr 15, 2020 at 9:52
  • a and b are documents inside the array B. Commented Apr 15, 2020 at 9:54
  • "B": [ {"a": { "_id": "ID0", "field": "X" }}, { "b": { "_id": "ID1", "field": "Y" }} ] Commented Apr 15, 2020 at 9:56

1 Answer 1

1

You can use $filter aggregation operator to achieve this :

db.collection.aggregate([
  {
    $addFields: {
      "B": {
        $filter: {
          input: "$B",
          as: "arr",
          cond: {
            $eq: [
              "$A._id",
              "$$arr._id"
            ]
          }
        }
      }
    }
  }
])

Test it here

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

Comments

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.