I have a document in a collection which have values in array.
{
"name": "ABC",
"details": [
{"color": "red", "price": 20000},
{"color": "black", "price": 22000},
{"color": "blue", "price": 21000}
]
},
{
"name": "XYZ",
"details": [
{"color": "yellow", "price": 10000},
{"color": "black", "price": 12000},
{"color": "green", "price": 11000}
]
},
{
"name": "CBD",
"details": [
{"color": "red", "price": 30000},
{"color": "pink", "price": 32000},
{"color": "blue", "price": 31000}
]
}
I want to filter data for color red and blue and need output like
{"name": "ABC", "color": "red", "price": 20000},
{"name": "ABC", "color": "blue", "price": 21000},
{"name": "CBD", "color": "red", "price": 30000},
{"name": "CBD", "color": "blue", "price": 31000}
what will the query for this…
I am able to get
{
"name": "ABC",
"details": [
{"color": "red", "price": 20000},
{"color": "blue", "price": 21000}
]
},
{
"name": "CBD",
"details": [
{"color": "red", "price": 30000},
{"color": "blue", "price": 31000}
]
}
but I want like
{"name": "ABC", "color": "red", "price": 20000},
{"name": "ABC", "color": "blue", "price": 21000},
{"name": "CBD", "color": "red", "price": 30000},
{"name": "CBD", "color": "blue", "price": 31000}
let me know the MongoDB query or JS/TS code to simplify array object…
6
Answers
You can use flatMap to get desired formatted data like below:
You can run the below js code (if you don’t mind the performance):
Using Array.flatMap() can do it ,below is reference for you,you can check at flattening-an-array-of-complex-objects-with-an-array-attribute
MongoDB’s $unwind operator can help –
Here’s an aggregate query –
I think, if you like to get good performance then this would be the best option:
Mongo Playground
By using aggregate the below query helps you alot.