MongoDB:更新存在的所有文档的字符串值

时间:2018-08-27 20:03:12

标签: arrays mongodb mongodb-query

collectionABC
/* 1 */
{
    "DealerId" : "39823398",
    "VehicleCategory" : [ 
        {
            "seqId" : "23987134983471982134HAD",
            "vehicleName" : "BMW",
            "vehicleImage" : "images/vehicle/270029.gif"
        }, 
        {
            "seqId" : "293874KJHKHKJH7878",
            "vehicleName" : "Audi",
            "vehicleImage" : "images/vehicle/27022398.gif"
        }
    ]
}

/* 2 */
{
    "DealerId" : "3987398",
    "VehicleCategory" : [ 
        {
            "seqId" : "2234423987134983471982134HAD",
            "vehicleName" : "Honda",
            "vehicleImage" : "images/vehicle/270029.gif"
        }, 
        {
            "seqId" : "9834293874KJHKHKJH7878",
            "vehicleName" : "Toyota",
            "vehicleImage" : "images/vehicle/27022398.gif"
        }
    ]
}

我有10万个具有上述格式的文档,并且对于所有现有文档,都需要从“ .gif”更新为“ .png”。其余所有内容应保持不变。

更新文档后,结果应类似于:

collectionABC
/* 1 */
{
    "DealerId" : "39823398",
    "VehicleCategory" : [ 
        {
            "seqId" : "23987134983471982134HAD",
            "vehicleName" : "BMW",
            "vehicleImage" : "images/vehicle/270029.png"
        }, 
        {
            "seqId" : "293874KJHKHKJH7878",
            "vehicleName" : "Audi",
            "vehicleImage" : "images/vehicle/27022398.png"
        }
    ]
}

/* 2 */
{
    "DealerId" : "3987398",
    "VehicleCategory" : [ 
        {
            "seqId" : "2234423987134983471982134HAD",
            "vehicleName" : "Honda",
            "vehicleImage" : "images/vehicle/270029.png"
        }, 
        {
            "seqId" : "9834293874KJHKHKJH7878",
            "vehicleName" : "Toyota",
            "vehicleImage" : "images/vehicle/27022398.png"
        }
    ]
}

有没有人想到我们如何在Mongo中做到这一点?非常感谢。

1 个答案:

答案 0 :(得分:0)

bulk_update = db.media.initializeUnorderedBulkOp()
db.media.find().forEach(function(e, i) {
   e.VehicleCategory.forEach(function(vehicle, index){
          vehicle.vehicleImage = vehicle.vehicleImage.replace('.gif','.png')
    })
   bulk_update.find({"DealerId": e.DealerId}).update({"$set": e})
})
bulk_update.execute()

如果有10万条记录,我建议根据您的MongoDB容量,一次选择10k的循环进行更新。

我是python家伙,如果没有使用正确的JS表示抱歉。