简体   繁体   中英

bulk update data into mongodb

I have below data in stored in my db.

[
    {
        date:'1-1-2016',
        users:[
            {
                'name':'james',
                'age':18
            },
            {
                'name':'alice',
                'age':20
            }
        ]
    },
    {
        date:'2-1-2016',
        users:[
            {
                'name':'james',
                'age':18
            },
            {
                'name':'alice',
                'age':20
            },
            {
                'name':'xiaomi',
                'age':29
            }
        ]
    }
]

I have a challenge to bulk update array of object efficiently.

My initial solution to update on single collection is

Users.update({date:'1-1-2016','user.name':'james'},{'$set':'users.$.age':5}})

So this will update james's age to 5 from 18, base on date and user's name.

But how to bulk update, says a range of date is given? use loop with above query? I think it's not efficient. Need guidance.

You can use $gte / $gt and $lte / $lt to match a date range:

db.users.update({
    date: {
        $gte: '1-1-2016',
        $lt: '31-1-2016'
    },
    'users.name': 'james'
}, { '$set': { 'users.$.age': 10 } }, { 'multi': true })

To bulk update with many couple of conditions name/age :

var data = [{ "name": "james", "age": 10 }, { "name": "alice", "age": 11 }];

var query = [];

for (var i = 0; i < data.length; i++) {

    query.push({
        updateMany: {
            "filter": {
                date: {
                    $gte: '1-1-2016',
                    $lt: '31-1-2016'
                },
                'users.name': data[i].name
            },
            "update": { '$set': { 'users.$.age': data[i].age } }
        }
    })
}

db.users.bulkWrite(query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM