0

The collection I'm trying to query has documents with the following structure -

{
  "_id": 1,
  "topA": "topAValue",
  "topB": "topBValue",
  "topC": "topCValue",
  "nestedDocArray": [
    {
      "attr1": "a",
      "attr2": "b",
      "attr3": "c"
    },
    {
      "attr1": "a5",
      "attr2": "b5",
      "attr3": "c5"
    },
    {
      "attr1": "a1000",
      "attr2": "b1000",
      "attr3": "c1000"
    }
  ]
}

I'm trying to query this document with "_id": 1 with a requirement to project only certain attributes. In addition to this, the requirement is to only fetch nestedDocArray which matches the condition "attr1": "a5".

The query I tried is as below -

db.testCollection.aggregate(
[
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$project": {
      "topA": 1,
      "nestedDocArray": {
        "$filter": {
          "input": "$nestedDocArray",
          "as": "nestedDocArray",
          "cond": {
            "$eq": [
              "$$nestedDocArray.attr1",
              "a5"
            ]
          }
        }
      }
    }
  }
]
);

The response of this query looks something like below -

{
  "_id": 1,
  "topA": "topAValue",
  "nestedDocArray": [
    {
      "attr1": "a5",
      "attr2": "b5",
      "attr3": "c5"
    }
  ]
}

This is fine. This has managed to project attributes topA and nestedDocArray. I further want to only project nestedDocArray.attr2. The output i'm looking for is like below.

{
  "_id": 1,
  "topA": "topAValue",
  "nestedDocArray": [
    {
      "attr2": "b5"
    }
  ]
}

How can I modify the query to achieve the same?

1

1 Answer 1

1

You can use $map with $filter to reshape your data:

db.testCollection.aggregate([
    {
        $match: { _id: 1 }
    },
    {
        $project: {
            topA: 1,
            nestedDocArray: {
                $map: {
                    input: {
                        $filter: {
                            input: "$nestedDocArray",
                            as: "nestedDocArray",
                            cond: {
                                $eq: [ "$$nestedDocArray.attr1", "a5" ]
                            }
                        }
                    },
                    as: "item",
                    in: {
                        attr2: "$$item.attr2"
                    }
                }
            }
        }
    }
])
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.