1

Suppose you have the following documents in my collection:

{
    "_id" : ObjectId("5ddb10ff6e25e6fec648df70"),
    "shapes" : [
        {
            "color" : [
                "blue",
                "red"
            ],
            "shape" : "square"
        },
        {
            "color" : [
                "red",
                "green"
            ],
            "shape" : "circle"
        }
    ],
    "name" : "customer1"
}

I have the following query:

db.customers
  .aggregate([
    { $match: { "shapes.color": "red" } },
    {
      $project: {
        shapes: {
          $filter: {
            input: "$shapes",
            as: "shape",
            cond: { $eq: ["$$shape.color", "red"] }
          }
        }
      }
    }
  ])
  .pretty();

Returns matched document:

{ "_id" : ObjectId("5ddb10ff6e25e6fec648df70"), "shapes" : [ ] }

But I was expecting this:

{
    "_id" : ObjectId("5ddb10629f3f949e3feddf19"),
    "shapes" : [
        {
            "color" : ["red"],
            "shape" : "square"
        },
        {
            "color" : ["red"],
            "shape" : "circle"
        }
    ]
}

How do I accomplish this?

1 Answer 1

1

You need to use $filter two times as you have two double nested arrays here

db.collection.aggregate([
  { "$match": { "shapes.color": "red" } },
  { "$project": {
    "shapes": {
      "$filter": {
        "input": {
          "$map": {
            "input": "$shapes",
            "in": {
              "shape": "$$this.shape",
              "color": {
                "$filter": {
                  "input": "$$this.color",
                  "cond": { "$eq": ["$$this", "red"] }
                }
              }
            }
          }
        },
        "as": "shape",
        "cond": { "$ne": ["$$shape.color", []] }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.