I have a document like below
{
"name" :{
"English": "AA",
"Bengali": "BB",
"Gujarati": "CC",
"Hindi": "DD"}
}
can I filter it based on the keys e.g. need to filter only on ‘English’ and ‘Hindi’ so the output should be
{
"name" :{
"English": "AA",
"Hindi": "DD"}
}
2
Answers
One way to do this is to first turn the object into an array of key-value pairs
[{ "k": "Bengali", "v": "BB" }, { "k": "English", "v": "AA" }...]
using$objectToArray
Then call
$filter
on the array and take only the ones you needFinally, convert that array back to an object using
$arrayToObject
playground
The simple option is to check for key existence and project only the necessary keys :
Playground
But the better option if you are going to use this filter often is to modify the keys to values as follow:
where you can do something faster like:
Assuming you create in advance an index on the "name.key" field.
playground