RichW
RichW

Reputation: 10942

MongoDB search - find newest within document

I've got a collection containing a few hundreds thousand documents, and I need to efficiently perform a check on one of those documents.

Here's an example of one of those documents:

{
    "_id" : ObjectId( "4ee9b4239641dce218030000" ),
    "last_seen" : Date( 1323938851402 ),
    "is" : {
        "4ee910de9641dc4906000000" : Date( 1323938851302 ),
        "4ee211df9621dc4206000000" : Date( 1323938851402 ),
        "4ef913de9631db4922000000" : Date( 1323938851102 ),
    }
}

I know the _id of the document is 4ee9b4239641dce218030000, and I need to determine whether the item in the "is" object with ID 4ee211df9621dc4206000000 is the newest out of the 3 and has a timestamp value of in the last 5 minutes.

If it helps the timestamp stored in "last_seen" will always be the same value as the latest record in the "is" object. Perhaps they could be compared?

Any thoughts on how this can be done with MongoDB efficiently?

Upvotes: 0

Views: 377

Answers (3)

Remon van Vliet
Remon van Vliet

Reputation: 18625

Why would you want to solve this with a query? You're already doing a find-by-id. Just write code that fetches the latest element from "is". Don't overcomplicate things by changing your schema or make arbitrary assumptions about recent activity timewindows when you can do it with one line of code in whatever language you prefer working with.

Upvotes: 1

milan
milan

Reputation: 12420

How about making "is" an array, sorted by Date, and then the query would be something like this:

`{$and : [ {_id : "4ee9b..." }, 
           {is[0].date: {$gt : now-5min }}, 
           {is[0]._id : "4ee21.." }]}`

You get no results unless item "4ee9b.." is the newest and less than 5min old.

Upvotes: 1

Nat
Nat

Reputation: 3727

best to keep "is" in another collection. If so, you can sort it anyway you like so find whether it's the latest id or not.

Upvotes: 0

Related Questions