COMMUNITY

MongoDB update from list

mongodb

(david mouton) #1

Hi,
I know this is not realy an Haxe related post, sorry for that.

public function updateUsersScore(users:Array<User>):Promise<WriteOpResult> {
        return new Promise(function(resolve, reject) {
            MongoClient.connect(Config.getInstance().db, function(error:MongoError, db:MongoDatabase) {
                db.collection(COLLECTION_NAME, null, null).update({_id:null}, users, { upsert : true }, function(error:MongoError, result:WriteOpResult):Void {
                    db.close();
                    if (error != null) {
                        Node.console.error(error);
                        reject(error);
                    } else {
                        resolve(result);
                    }
                });
            });
        });
    }

According to this function name, i want to update users score. I have an Array and for each user._id i want to set user.score.
Is it possible to do it in one request or should i iterate over my list ?


(david mouton) #2

To myself : it’s possible to use a Bulk to perform this request :

 var bulk = db.collection(COLLECTION_NAME, null, null).initializeUnorderedBulkOp();
                    for (user in users) {
                        var query:Dynamic = {};
                        Logger.info("score " + user.score);
                        query.$set = { "score": user.score };
                        bulk.find({bot:user.bot}).upsert().update(query);
                    }
                    var result:BulkWriteResult = bulk.execute();
                    resolve(result);