How to stop a long running query, on few documents?

How to stop an aggregation query while running?
I have an app that users write their own queries, app receives the query as String and runs the query, so i don’t have control over the queries. And a user can make slow queries that i can’t stop.

I tried 2 ways

  • maxTime
  • killOp

They both worked if the collection had many documents, but if it had like 20 documents that i tested, even if it took a very long time > 10 seconds (i tested with 2 nested maps) it didn’t stop.

Currently, the only option i have is to shut down the MongoDB server(when i detect a opid that runs long time) and restart it.

The problem is not just the CPU and the time, it’s the memory also, if this query use all the memory mongod process auto-terminates, but it’s already too late(all memory is used).

Maybe there are other ways or options to put on config file that i don’t know.

If you want to an example query,to try it, try the bellow in like 20 documents.Change the range also for even slower per-document queries.

aggregate(
[{"$set": 
  {"a": 
   {"$size": 
    {"$map": 
     {"input": {"$range": [0, 10000]},
       "in": 
        {"$map": {"input": {"$range": [0, 10000]}, "in": 1, "as": "t1"}},
        "as": "t"}}}}}])

I am using

  • MongoDB 5 community edition
  • standalone on localhost
  • no authentication
  • ubuntu 20.04 lts
  • on my 8GB laptop

Thank you