Search code examples
mongodbmongodb-queryaggregation-frameworkprojection

MongoDB Project - return data only if $elemMatch Exist


Hello Good Developers,

I am facing a situation in MongoDB where I've JSON Data like this

[{
    "id": "GLOBAL_EDUCATION",
    "general_name": "GLOBAL_EDUCATION",
    "display_name": "GLOBAL_EDUCATION",
    "profile_section_id": 0,
    "translated": [
      {
        "con_lang": "US-EN",
        "country_code": "US",
        "language_code": "EN",
        "text": "What is the highest level of education you have completed?",
        "hint": null
      },
      {
        "con_lang": "US-ES",
        "country_code": "US",
        "language_code": "ES",
        "text": "\u00bfCu\u00e1l es su nivel de educaci\u00f3n?",
        "hint": null
      }...
    {
     ....
    }
]

I am projecting result using the following query :

db.collection.find({

},
{
  _id: 0,
  id: 1,
  general_name: 1,
  translated: {
    $elemMatch: {
      con_lang: "US-EN"
    }
  }
})

here's a fiddle for the same: https://mongoplayground.net/p/I99ZXBfXIut

I want those records who don't match $elemMatch don't get returned at all.

In the fiddle output, you can see that the second item doesn't have translated attribute, In this case, I don't want the second Item at all to be returned.

Output from Fiddle

I am using Laravel as Backend Tech, I can filter out those records using PHP, but there are lots of records returned, and I think filtering using PHP is not the best option.


Solution

  • You need to use $elemMatch in the first parameter

    db.collection.find({
      translated: {
        $elemMatch: {
          con_lang: "IT-EN"
        }
      }
    })
    

    MongoPlayground