Search code examples
collectionsmongodbdocuments

MongoDB - How to query Embedded Documents from a collection


Gurus - I'm stuck in a situation that I can't figure out how I can query from the following collection "users", it has 2 embedded documents "signup" and "activity":

{
    "appid": 2,
    "userid": 404915,
    "signup": {
        "dt": "2010-12-28",
        "platform": 2 
    },
    "activity": {
        {
            "dt": "2010-12-28",
            "platform": 3,
            "login_count": 8,
            "game_completed": 13 
        },
        {
            "dt": "2010-12-30",
            "platform": 3,
            "login_count": 8,
            "game_completed": 13 
        } ,
        {
            "dt": "2010-12-31",
            "platform": 3,
            "login_count": 8,
            "game_completed": 13 
        } 
    }
},{"appid":2,"userid":404915...}

I need to query:

unique logins of users who signed up between Date and Date+7 and logged in within Date

Then:

Unique logins of users who signed up between Date and Date+7, and logged in between Date+7 and Date+14

PLEASE PLEASE Guide me how I can achieve this any example/sample? based on this will be really helpful :-)

Thanks a lot!


Solution

  • Here is how you get the result for your first query:

    var start = new Date(2010, 11, 25);
    var end = new Date(2010, 12, 1);
    
    db.users.distinct("userid", {"signup.dt" : {$gte: start, $lte: end},
          "activity" : {"$elemMatch" : { dt: {$gte: start, $lte: end}}}});
    

    The second is like it with adding 7 days to the start and end date to the dates after activity.