I need to group based on dynamic keys. So I’m using $objectToArray to query on dynamic keys.
But I need to filter out the documents based on a condition so as to reduce the input going to $objectToArray. Because I have millions of documents and I just want only a subset of the object fields to be fed to the $objectToArray operator.
My aim is to get better query performance by reducing the amount of data passed to $objectToArray operator
A sample format of my MongoDB schema:
[
{
"fields": {
"field_1": { /* dynamic key */
"name": "f1",
"first": {
"check": true
}
},
"field_2": { /* dynamic key */
"name": "f2",
"second": {
"check": true
}
},
"description": "abc",
"summary": {
"val": "xyz"
}
}
},
{
"fields": {
"field_1": { /* dynamic key */
"name": "f1",
"second": {
"check": false
}
},
"field_2": null, /* dynamic key */
"field_3": { /* dynamic key */
"name": "f3",
"second": {
"check": true
},
"first": {
"check": true
}
},
"description": "lmn",
"summary": {
"val": "abc"
}
}
}
]
There are also many fields other than dynamic fields.
I need to filter out the documents before being fed to $objectToArray operator based on the following condition:
fields.<*dynamicKey*>.first
exists
ORfields.<*dynamicKey*>.second
exists
Expected output:
[
{
"fields": {
"field_1": {
"name": "f1",
"first": {
"check": true
}
},
"field_2": {
"name": "f2",
"second": {
"check": true
}
}
}
},
{
"fields": {
"field_1": {
"name": "f1",
"second": {
"check": false
}
},
"field_3": {
"name": "f3",
"second": {
"check": true
},
"first": {
"check": true
}
}
}
}
]
How can I achieve this use case without changing my document structure?
db.collection.aggregate([
{
I need a stage to filter out documents here
},
{
$project: {
data: {
$objectToArray: "$fields"
}
}
}