MongoDB 聚合框架 - 动态字段重命名 [英] MongoDB Aggregation Framework - Dynamic Field Rename

查看:21
本文介绍了MongoDB 聚合框架 - 动态字段重命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 MongoDB 聚合框架非常强大 - 将对象展平似乎是一个不错的选择.我的架构在一个名为 materials 的数组中使用了一个子对象数组.material 的数量是可变的,但特定字段 category 在数组中的对象中将是唯一的.我想使用聚合框架来展平结构并根据 category 字段的值动态重命名字段.我找不到使用 $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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆