ayyayyekokojambo
ayyayyekokojambo

Reputation: 1245

How to get documents where KEY is greater than X

i am recording user's daily usage of my platform.

structures of documents in mongodb are like that:

_id: X
day1:{
    loginCount = 4
    someDict { x:y, z:m }
    }
day2:{
    loginCount = 5
    someDict { a:b, c:d }
    } 

then, i need to get last 2 day's user stats which belongs to user X.

how can i get values whose days are greater than two days ago? (like using '$gte' command?)

Upvotes: 0

Views: 97

Answers (2)

RickyA
RickyA

Reputation: 16029

Ok, if you insist on this scheme try this:

{
_id: Usemongokeyhere
userid: X
days: [
         {day:IsoDate(2013-08-12 00:00), 
          loginCount: 10,
          #morestuff
         },
         {day:IsoDate(2013-08-13 00:00), 
          loginCount: 11,
          #morestuff
         },
      ]
},
#more users

Then you can query like:

db.items.find(
    {"days.day":{$gte:ISODate("2013-08-30T00:00:00.000Z"),
                $lt: ISODate("2013-08-31T00:00:00.000Z")
                }
    }
)

Upvotes: 3

fgakk
fgakk

Reputation: 1307

Unless there is any change in the question, i am answering based on this schema.

_id: X
day1:{
   loginCount:4
   someDict:{ x:y, z:m }
}
day2:{
  loginCount:5
  someDict:{ a:b, c:d }
} 

Answer:

last 2 day's user stats which belongs to user X.

You cannot get it from mongo side with operators like $gte, with this structure, because you get the whole days when do query for user X. The document contains information about all days and keeping dynamic values as keys is in my opinion a bad practice. You can retrieve a documents by defining fields like db.collection.find({_id:X},{day1:1,day2:1})

However you have to know what the keys are and i am not sure how you keep day1 and day2 as key iso date, timestamp? Depending on how you hold it, you can write fields on the query by writing yesterday and before yesterday as date string or timestamp and get your required information.

Upvotes: 2

Related Questions