简体   繁体   中英

Mongodb query taking too long

I'm trying to get the hang of Mongodb, and right now, I have a very small collection with only a few hundred records, from which I'd like to update some fields dynamically in the future with javascript. But, although right now there are too few documents, the below query and update takes a minimum of 24 secs. I don't think it's gonna be any use to me once we go into production and have loads of documents to update. Anyone could help me with what is wrong with my code below?

Thanks in advance

var d = new Date();
var sapm = 1.8;
i = 0;
db.getCollection('content').find().forEach(function(x) {

    var window = (d - x.updated_at) / (24 * 60 * 60 * 1000);
    var feed = db.content.find({}, {
        _id: x._id
    });
    var comment = x.total_comment || 0;
    var up = x.total_up || 0;
    var interaction = up + (comment / 2);
    var hourage = (d - (x.updated_at));
    var rank = interaction / Math.pow((hourage - 4) * sapm);

    if (window <= 15) {
        db.content.update({
            '_id': x._id
        }, {

            $set: {
                "rank": rank,
            }
        }, {
            multi: true
        });
    }
});

Your query is fast, it's the updating each document individually that is taking time.

You should look to push all docs to update into an array, then use something like async.js to save / update in parallel.

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