Tushar Kale
Tushar Kale

Reputation: 169

How to find matching elements from an array of objects using mongoDB query

I want to find all elements matching product "bat". My structure for database is as follows

[
  {
    "key": 1,
    "productArray" : [
      {
         "requirementId": 5,
         "product": "bat"
      },
      {
        "requirementId": 6,
        "product": "Pen"
      },
     ]
  },
  {
    "key": 2
  },
  {
    "key": 3,
    "productArray": [
      {
        "requirementId": 1,
        "product": "bat"
      },
      {
        "requirementId": 2,
        "product": "Pen"
      },
      {
        "requirementId": 3,
        "product": "bat"
      },
      {
        "requirementId": 4,
        "product": "bat"
      }
    ]
  }
]

I have tried the following query but this query is returning only one matching element.

db.collection.find({"key": 3}, {"productArray": {"$elemMatch": { "product": "bat"}}})

result of above query is as follows

[
 {
    "_id": ObjectId("5a934e000102030405000002"),
    "productArray": [
      {
        "product": "bat",
        "requirementId": 1
      }
    ]
 }
]

Can I get expected output for my problem is as follows using mongodb query Or should I use another approach for my case:

My expected output is as follows

[
  {
    "productArray": [
    {
      "requirementId": 1,
      "product": "bat"
    },
    {
      "requirementId": 3,
      "product": "bat"
    },
    {
      "requirementId": 4,
      "product": "bat"
    }
    ]
 }
]

Upvotes: 0

Views: 263

Answers (1)

user12582392
user12582392

Reputation:

As you found, $elemMatch but also $ are lazy operators and return the first element that matches.

You could add a pipeline in find (mongoDB 4.4+) but aggregation is better supported:

db.collection.aggregate({
  $match: {
    key: 3
  }
},
{
  $project: {
    productArray: {
      "$filter": {
        "input": "$productArray",
        "as": "p",
        "cond": {
          $eq: [
            "$$p.product",
            "bat"
          ]
        }
      }
    }
  }
})

Live version

Upvotes: 1

Related Questions