0

I have a mongodb that will be storing visitor data. I need to delete the data after ten minutes of not being active and will run a command through a cron. How would I do this?

Currently the collection is setup like so:

{ "_id" : ObjectId("4fd33e0b0feeda3b2406f6be"), "name" : "Dugley Reanimator", "updated" : "Some form of timestmap" }

How should I go about storing a timestamp that I search the collection with I.E for my MySql version:

$sql = mysql_query('DELETE FROM `visitors` WHERE NOW() > DATE_ADD(`last_seen`, INTERVAL 10 MINUTE)');
Community
  • 1
  • 1
Michael
  • 573
  • 2
  • 12
  • 26
  • Default from pecl install mongo – Michael Jun 09 '12 at 12:30
  • could you clarify if each document in the collection represents a session or just a lot entry? In other words, do you constantly update the "updated" field or do you create a new entry when someone does something new on the site? – Asya Kamsky Jun 10 '12 at 04:56

3 Answers3

1

The best way to do it (if the timestamp is the same when you insert) its by using the _id field.

The _id field can indicate you the time, and you can do a $lte query to delete old values.

I've written about it here: http://blog.dicarsio.com/post/10739857186/quick-snippet-get-creation-time-from-id-on-mongodb

dicarsio
  • 472
  • 2
  • 6
1

The ObjectId has a timestamp component to it. see the docs here. This essentially gives you a free insert time that you can use for sorting and querying.

The mongodb drives should give you a way to created an ObjectId off of a timestamp.

In Python:

gen_time = datetime.datetime(2010, 1, 1)
dummy_id = ObjectId.from_datetime(gen_time)

In Java:

Date d = new Date(some timestamp in ms);
ObjectId id = new ObjectId(d)

So once you've created an ObjectId based on "10 minutes ago" you can do a delete query using $lt

in the js console it would be:

db.collectionName.remove({_id: {$lt: <Your Object Id that represents 10 minutes ago>})   
phatduckk
  • 1,775
  • 1
  • 14
  • 17
0

Your driver will use a MongoDate time (this may map to a more native representation in PHP).
You can then query using something like the following mongo statement:

db.myCollection.find({updated : { $lte : new ISODate("2012-06-09T16:22:50Z") } })

A rough translation for PHP would be:

$search = array(
  'updated' => array(
    '$lte' => new MongoDate($tenMinutesAgo))
);
$collection->find($search)

Or (Caveat: not tested):

$tenMinutesAgo = new DateTime();
$tenMinutesAgo->modify('-10 minutes');

$search = array('updated' => array('$lte' => $tenMinutesAgo));
$collection->find($search)
stew
  • 491
  • 3
  • 7