如何将现有字段及其值设置为数组的对象

How to set existing field and their value to array's objects

我是 MongoDB 的新手。我下面有一个对象

{
        "_id" : "ABCDEFGH1234",
        "level" : 0.6,
        "pumps" : [
                {
                        "pumpNo" : 1
                },
                {
                        "pumpNo" : 2
                }
        ]
}

我只想像这样移动水平场来泵送数组的对象

{
        "_id" : "ABCDEFGH1234",
        "pumps" : [
                {
                        "pumpNo" : 1,
                        "level" : 0.6
                },
                {
                        "pumpNo" : 2,
                        "level" : 0.6
                }
        ]
}

我查看了 MongoDB 文档中的汇总部分,但没有找到任何内容。在 SQL 中,通过 JOIN 或 SUB 查询我可以做到,但这里是 No-SQL

你能帮我解决这个问题吗?谢谢

试穿尺码:

db.foo.aggregate([
    //  Run the existing pumps array through $map and for each                                      
    //  item (the "in" clause), create a doc with the existing                                      
    //  pumpNo and bring in the level field from doc.  All "peer"                                   
    //  fields to 'pumps' are addressable as $field.                                                
    //  By $projecting to a same-named field (pumps), we effectively                                
    //  overwrite the old pumps array with the new.                                                 
    {$project: {pumps: {$map: {
        input: "$pumps",
        as: "z",
        in: {pumpNo:"$$z.pumpNo", level:"$level"}
        }}  
    }}
]);

强烈建议您探索 $map$reduce$concatArrays$slice 和其他使 MongoDB 查询语言与众不同的数组函数的强大功能来自 SQL.

中更多 scalar-based 的方法