Selecting a field that i don’t know its name,but its name is stored in the document as value

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" }

Thank you for the reply :slight_smile:
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