Home > Mobile >  How to query nested objects
How to query nested objects

Time:02-18

MongoDB I have one document, I need to get one object, if locale.en then it will return that info if locale.fr' then it will return that info

{
   "locale": {
        "en": {
          "dashboard": {
            "DASHBOARD_TITLE": "Some title"
          }
        },
        "fr": {
          "dashboard": {
            "DASHBOARD_TITLE": "Some title french"
          }
        },
        "pr": {
          "dashboard": {
            "DASHBOARD_TITLE": "Some title portugues"
          }
        }
      }
    }

How to query this specific object?

db.collectionName.find({locale.en})

enter image description here

CodePudding user response:

You can achieve this using aggregation

Assuming your object has key locale like this

{
"_id": <Some Object Id>,
"locale": {
  "en": {
    "dashboard": {
      "DASHBOARD_TITLE": "Some title"
    }
  },
  "fr": {
    "dashboard": {
      "DASHBOARD_TITLE": "Some title french"
    }
  },
  "pr": {
    "dashboard": {
      "DASHBOARD_TITLE": "Some title portugues"
    }
  }
 }
}

Then aggregation would be

[{
"$project": {
  "locale": {
    "$arrayToObject": {
      "$filter": {
        "input": {
          "$objectToArray": "$locale"
        },
        "as": "el",
        "cond": {
          $eq: [
            "$$el.k",
            "en"
          ]
        }
      }
    }
  }
 }
}]

Just pass your locale in $eq array as second value, I've passed en you can use variable here to build query

Playground: https://mongoplayground.net/p/7ZHIUx_j1GY

Answer on this question explains the pipeline in detail MongoDB projection on specific nested properties

  • Related