0

I try to abort a query after it works specific time. So ı use mongodb maxTimeMS() method for my query. But it is not working.

I except that this query will stop after 5 second but keep working. how ı terminate my query after it works specific time

var sum = 0 ;
var inbox=db.getMongo().getDB("xxxx").getCollection("Inbox");
var oldInbox=db.getMongo().getDB("xxxx").getCollection("oldInbox");
var inboxCount = inbox.count();
var oldCount = oldInbox.count();
var dif = inboxCount - oldCount ;
if ( dif > 10000000 ){
var cursor = inbox.find().maxTimeMS(5000);
cursor.sort({_id : -1}).forEach(function(uidDoc) {
    var uid = uidDoc.uid;
    var docsToMigrate = [];
    var idsToRemove = [];
    inbox.find({uid : uid}).sort({_id : -1}).skip(10).forEach(function(doc) {
        docsToMigrate.push(doc);
        idsToRemove.push(doc._id);
        var x = doc._id;
    });
    oldInbox.insert(docsToMigrate);
    inbox.remove({_id : {$in : idsToRemove}});
    sum = sum + idsToRemove.length;
    if ( x = 0 )
    {
        print(sum);
        cursor.close();
    }
});
};
user10651098
  • 75
  • 1
  • 7

1 Answers1

0

Based on documentation here, maxTimeMS is a limit on processing time within the database. This will cover query planning, execution, and data serialization, but the timer stops when the cursor is idle. This is not wall time and means that it does not account for the execution time within your forEach callback. Since your query seems quite simple, it will likely take much more time than the maxTimeMS limit for it to stop.

So to answer your question, you'll need to keep a timer elsewhere and manage it yourself using paginated queries.

kmdreko
  • 42,554
  • 6
  • 57
  • 106