简体   繁体   中英

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?)

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")
                }
    }
)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM