MongoDB聚合框架-动态字段重命名 [英] MongoDB Aggregation Framework - Dynamic Field Rename
问题描述
我发现mongodb聚合框架非常强大-展平对象似乎是一个不错的选择.我的模式使用称为材料的数组中的子对象数组.材料的数量是可变的,但是特定字段(类别)在阵列中的对象之间将是唯一的.我想使用聚合框架来展平结构并根据类别字段的值动态重命名字段.我找不到一个简单的方法来使用$ project和$ cond来完成此任务.有办法吗?
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:
例如{'materials.name':'XYZ'}会撤回找到XYZ的所有文档.
e.g. { 'materials.name' : 'XYZ' } pulls back any document where XYZ is found.
例如文档前后的数量
{
"_id" : ObjectId("123456"),
"materials" : [
{
"name" : "XYZ",
"type" : "Red",
...
"category" : "A"
},
{
"name" : "ZYX",
"type" : "Blue",
...
"category" : "B"
}]
}
至
{
"material_A_name" : "XYZ",
"material_A_type" : "Red",
...
"material_B_name" : "ZYX",
"material_B_type" : "Blue",
...
}
推荐答案
jira中有这样的请求 https://jira.mongodb.org/browse/SERVER-5947 -如果您希望使用此功能,请将它投票.
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.
这篇关于MongoDB聚合框架-动态字段重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!