MongoDB request for a document older than 30 seconds

Does anyone have a good approach for querying the collection for documents older than 30 seconds. I am creating a cleaning worker who notes that the items failed after they were in a certain state for more than 30 seconds.

Not important, but I use mongojs for this.

Each document has a time associated with it created.

+4
source share
4 answers

We assume that your document has created_ateither a similar field that has a time at which it was inserted or otherwise changed, depending on what is important to you.

Instead of repeating the results, you can see the option multito update to apply the changes to all documents that match your request. Setting the time you want to view should be pretty simple

In the shell syntax, which should be almost the same as the driver:

db.collection.update({
     created_at: {$lt: time },
     state: oldstate 
},
{$set: { state: newstate } }, false, true )

The first falserelates to the upserts, which makes no sense in the use, and the second trueto multiupdate the document.

, , , total size time to live, .

+6

mongo:

db.requests.find({created: {$lt: new Date((new Date())-1000*60*60*72)}}).count()

... 72 ( "" "72 * 60 * 60 * 1000" ). 30 1000 * 30.

+7

- :

var d = new Date();
d.setSeconds(d.getSeconds() - 30);

db.mycollection.find({ created_at: { $lt: d } }).forEach(function(err, doc) {} );
+3

TTL . , x , . : https://docs.mongodb.org/manual/core/index-ttl/

:

db.yourCollection.createIndex({ created:1 }, { expireAfterSeconds: 30 } )

+2

Source: https://habr.com/ru/post/1525521/


All Articles