【问题标题】:Checking 2 fields in array and combine two arrays to get single array Mongodb检查数组中的 2 个字段并组合两个数组以获得单个数组 Mongodb
【发布时间】:2017-02-25 13:53:20
【问题描述】:

我有一个收藏

{
_id:"123",
obj1:[{defaultNo:1,fine:100},{defaultNo:3,fine:10}],
obj2:[{default:1},{default:2},{default:3}]
}

我尝试过这样的事情,但我被卡住了

db.collection.aggregate([
// Match possible documents
{ "$match": {
    "_id" : "123"
}},
{ "$unwind": "$obj1" },{
    "$group": {
    "_id": { 
        "document": "$_id", 
        "objfirst" : "$obj1.defaultNo",
        "objlast":"$obj2"
    },

} }  ])

这给了我一个结果

   "_id" : {
                "document" : "123",
                "objfirst" : "1",
                "objlast" : [{default:1},{default:2},{default:3}]
},  "_id" : {
                "document" : "123",
                "objfirst" : "2",
                "objlast" : [{default:1},{default:2},{default:3}]
},

但我一直在寻找这种类型的结果,例如将两个数组与字段值合并

{
_id:"123",
object:[{default:1,fine100},{default:2,fine:false},{default:3,fine:10}]
}

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    我建议您查看 $concatArrays 运算符,它可以满足您的需求。

    如果您在 shell 中运行以下查询,

    db.collection.aggregate([
      {$match:{_id:"123"}},
      {$project:{object:{$concatArrays:["$obj1","$obj2"]}}}
    ])
    

    输出将是(使用您的示例输入文档与您想要的输出非常匹配)

    { 
        "_id" : "123", 
        "object" : [
            {
                "default" : 1.0, 
                "fine" : 100.0
            }, 
            {
                "default" : 3.0, 
                "fine" : 10.0
            }, 
            {
                "default" : 1.0
            }, 
            {
                "default" : 2.0
            }, 
            {
                "default" : 3.0
            }
        ]
    }
    

    更新:

    $match 添加到聚合管道以匹配 OP 的尝试。

    【讨论】:

    • 很抱歉,如果两个字段的名称在一种情况下为 defaultNo 而在另一种情况下为 default 不同,那么更好的方法是什么..
    猜你喜欢
    • 2014-02-27
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2021-07-16
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多