Mongodb find occurrences

gilamran Source

I have a huge collection of log events on the monogdb, each event has a unique id.

A very simple example:

  • user login
  • ...
  • user created a product
  • user created a product
  • user renamed a product
  • user created a product
  • ...
  • user logged out

I want to find a specific occurrence (say the 3rd product create event) and I want to fetch 10 events before and 10 events after this occurrence. Is that even possible with mongodb?

I'm using Mongoose with NodeJs

Thanks!

node.jsmongodb

Answers

answered 2 years ago Dushyant Bangal #1

This will work if you have unique timestamp for the events:

Model.find({"event": "user created a product"}).skip(2).exec(function (err, docs)
{
    var myEvent = docs[0];

    Model.find({timestamp: {$gt: myEvent.timestamp}}).limit(10).exec(function (error, records)
    {
        console.log(records);
    });
});

Update: If you don't have timestamp for each event (which would be really wrong), this should work:

Model.find({"event": "user created a product"}).skip(2).exec(function (err, docs)
{
    var myEvent = docs[0];

    Model.find({"_id": { "$lt" : myEvent._id}}).count().exec(function(error,count)
    {
        Model.find().skip(count).limit(10).exec(function(e,records)
        {
            console.log(records);
        })
    })
});

comments powered by Disqus