Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 938
Syed Kamran Haider Avatar asked Nov 25 '10 14:11

Syed Kamran Haider


People also ask

Is a MongoDB method to retrieve documents from a collection?

find() is a function that retrieves documents from a MongoDB database. In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection.

How do I query a nested array in MongoDB?

Specify a Query Condition on a Field Embedded in an Array of Documents. If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot ( . ) and the name of the field in the nested document.

Which query helps in fetching documents from collection?

The MongoDB find query is an in-built function which is used to retrieve the documents in the collection.


1 Answers

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.

like image 105
Jeff the Bear Avatar answered Sep 21 '22 03:09

Jeff the Bear