如何使用Node.js在MongoDB的嵌套数组中将数组元素推入每个数组元素

时间:2018-09-01 13:56:16

标签: node.js mongodb mongoose mongodb-query

我想将数组元素作为mongodb中嵌套数组中的每个元素推送,我正在使用的代码是这样:

$push:{
    "websites.$.ads":{
        "ad_type":{"$each":["320x40","480x30"]}
    }
}

我具有以下架构设计:

_id:KLNkl23klmKLM233mKLM233
websites:[     
    {  
        _id:"xyz"  
        ads:[ 
            ad_type:""  
        ]   
    },
    {  
        _id:"xyz"  
        ads:[ 
            ad_type:""  
        ]   
    }
]                                     

我最后想要得到的是

{   
  "_id" : ObjectId("some id"),   
  "websites" : [  
             { 
                 "ads" : [ 
                     { _id:"asdfasdf" , "ad_type" : "some value" },
                     { _id:"asdfasdf" , "ad_type" : "some value" },
                     { _id:"asdfasdf" , "ad_type" : "some value" }  
                 ] 
             } 
   ] 
 }

1 个答案:

答案 0 :(得分:0)

您可以使用positional argument的数组更新。我尝试使用以下语法使其正常工作,并在下面输出

db.coll.update({}, {
    $push: {
        'websites.$[].ads': {
            $each: [{
                    _id: 'some_id',
                    ad_type: 'some value'
                }
            ]
        }
    }
})

输出

{
        "_id": ObjectId("SOME_MAIN_ID"),
        "websites": [{
                "ads": [{
                        "_id": "some_id",
                        "ad_type": "some value"
                    }, {
                        "_id": "some_id_1",
                        "ad_type": "some value_1"
                    }
                ]
            }
        ]
    }

编辑为更改数组

db.coll.update({}, {
    $set: {
        'websites.$[].ads': [{
                _id: 'some_id_1',
                ad_type: 'some value_1'
            }
        ]
    }
})
WriteResult({
    "nMatched": 1,
    "nUpserted": 0,
    "nModified": 1
})
db.coll.find() {
    "_id": 'SOME_MAIN_ID',
    "websites": [{
            "ads": [{
                    "_id": "some_id_1",
                    "ad_type": "some value_1"
                }
            ]
        }
    ]
}
db.coll.update({}, {
    $set: {
        ' websites.$[].ads ': [{
                _id: ' some_id_1 ',
                ad_type: ' some value_1 '
            }, {
                _id: ' some_other_id_2 ',
                ad_type: ' some_other_type '
            }
        ]
    }
})

WriteResult({
    "nMatched": 1,
    "nUpserted": 0,
    "nModified": 1
})
db.coll.find() {
    "_id": 'SOME_MAIN_ID',
    "websites": [{
            "ads": [{
                    "_id": "some_id_1",
                    "ad_type": "some value_1"
                }, {
                    "_id": "some_other_id_2",
                    "ad_type": "some_other_type"
                }
            ]
        }
    ]
}