Hi everyone! I’m relatively new to using mongodb with pure queries, so it may be something stupid and obvious, but still I have a trouble dealing with it.
I have some kind of complex query using aggregate pipeline, and in one place, I need to compare two fields of same document. The thing is that one of the fields name is variable. So as far as I’ve read, there is a possibility of using $objectToArray
to convert everything to array inside necessary struct and just make $elemMatch
. However, one of the defined fields already have a necessary key for this dynamic field.
For example, consider this collection:
[
{
"id": 2,
"field_bb": {
"id": 2,
},
"field_c": "field_bb",
},
{
"id": 2,
"field_b2": {
"id": 2,
},
"field_c": "field_b2",
},
{
"id": 3,
"field_bsss": {
"id": 2,
},
"field_c": "field_bsss",
}
]
And I need to find each document who has equal id
and variable_field.id
. But actual variable_field is defined inside constant field_c
, so there may be some kind of optimizations, not iterating all over the document keys. So for example, in JS doing something like that will look as simple as obj[obj.field_c].id === obj.id
.
So, is it actually possible to make such things working smoothly using MongoDB Aggregate? Any help would be appreciated!