Takis
(Takis )
July 16, 2020, 1:45am
1
Hello
I want to select “aname87” field but i don’t know its name,i only know that “name” field value has the name.
Is there a simple solution to make that reference to that field?
Something like that project("$" + $name) = project("$aname87")
{
“name” : “aname87” ,
“aname87” : “avalue”
}
Thank you
Hello @Takis , welcome to the forum.
You can do it like this using the $objectToArray aggregation operator.
db.collection.aggregate( [
{
$addFields: { obj_as_arr: { $objectToArray: "$$ROOT" } }
},
{
$unwind: "$obj_as_arr"
},
{
$project: {
_id: 0,
field_name: "$obj_as_arr.k",
field_value: { $cond: [ { $eq: [ "$obj_as_arr.k", "$name" ] }, "$obj_as_arr.v", "$$REMOVE" ] }
}
},
{
$match: {
field_value: { $exists: true }
}
}
] )
The output:
{ "field_name" : "aname87", "field_value" : "avalue" }
Takis
(Takis )
July 16, 2020, 12:33pm
3
Thank you for the reply
I thought that object to array might have helped.
I was hoping that i could do something like eval(construct_reference)
Both construct and eval inside the database (not the client)
I think i will just use arrays to store unknown values(not fields) and search on them
1 Like