简体   繁体   中英

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"
    }
    ]
 }
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM