Search code examples
javascriptmongodbquery-optimization

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
        });
    }
});

Solution

  • 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.