问题
I am finding the mongodb aggregation framework to be extremely powerful - it seems like a good option to flatten out an object. My schema uses a an array of sub objects in an array called materials. The number of materials is variable, but a specific field (category) will be unique across objects in the array. I would like to use the aggregation framework to flatten the structure and dynamically rename the fields based on the value of the category field. I could not find an easy way to accomplish this using a $project along with $cond. Is there a way?
The reason for the array of material objects is to allow simple searching:
e.g. { 'materials.name' : 'XYZ' } pulls back any document where XYZ is found.
E.g. of before and after document
{
"_id" : ObjectId("123456"),
"materials" : [
{
"name" : "XYZ",
"type" : "Red",
...
"category" : "A"
},
{
"name" : "ZYX",
"type" : "Blue",
...
"category" : "B"
}]
}
to
{
"material_A_name" : "XYZ",
"material_A_type" : "Red",
...
"material_B_name" : "ZYX",
"material_B_type" : "Blue",
...
}
回答1:
There is a request for something like this in jira https://jira.mongodb.org/browse/SERVER-5947 - vote it up if you would like to have this feature.
Meanwhile, there is a work-around if you know up front what the possible values of the keys will be (i.e. all unique values of "category") and I have some sample code on it on my blog.
来源:https://stackoverflow.com/questions/15754558/mongodb-aggregation-framework-dynamic-field-rename