Romeo Mihalcea
Romeo Mihalcea

Reputation: 10252

mongodb find on nested objects

I have many documents with the following structure:

{
    _id: ObjectId("519af935c1a9f8094f0002aa"),
    messages: [{
          message: "Message A",
          timestamp: 1369130219638
      },
      {
          message: "Message B",
          timestamp: 1369130249638
      },
      {
          message: "Message C",
          timestamp: 1369130291638
      }
    ]
}

...and I don't know how to query all documents that have the last message posted more than 1 hour ago. Something like: get all documents where timestamp < now() - 3600 where now() is the current timestamp.

Any ideas?

Upvotes: 3

Views: 2192

Answers (1)

Tarang
Tarang

Reputation: 75945

Document Query

A mongodb query will return the document containing the message with the timestamp. You can do

var tofilter = Messages.find({"messages.timestamp":{$lt:new Date().getTime()-3600*1000}});

Now you have to get rid of all the messages in each document which dont match the date/time query:

The above query will return all documents matching the criteria but they will contain all the messages in each one no matter what timestamp they have, as long as one of them matches the criteria.

Filter Messages

var results = tofilter.map(function(doc) {
                var messages = doc.messages;
                return _.filter(messages, function(message) {
                    return (message.timestamp < new Date().getTime()-3600*1000)
                });
            });

so now results will contain all your mongodb documents, containing only messages which match the date/time query

*Note new Date.getTime() returns the timestamp in js format, which is quoted in milliseconds, so 3600 needs to be multiplied by 1000 to get 1 hour in ms.

Upvotes: 3

Related Questions