0

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

2
  • do you have a variable called locale with a property called en - oh, wait, that's not valid syntax at all anyway - that's not how you pass anything in javascript Commented Feb 18, 2022 at 5:20
  • I just updated with mongo image Commented Feb 18, 2022 at 5:26

1 Answer 1

1

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

Playground: https://mongoplayground.net/p/wuv4axIMzCc

Dynamic query : https://mongoplayground.net/p/5ouZif-MIry

Sign up to request clarification or add additional context in comments.

2 Comments

how to bind the dynamic properties. for eg: "locale": { this property needs to change from locale.$parm1: {
@Rijo I am not sure what you are trying to do. Also the dynamic query link you added in answer is not a right mongo query, consider removing it from answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.