Sunday, September 7, 2014

M101J: MongoDB for Java Developers Homework 5.1

M101J: MongoDB for Java Developers Homework 5.1

Question: Finding the most frequent author of comments on your blog.

 Solution:

you need to use webshell to find the most frequent author of comments 

Step 1:

Understand Structure of posts collection

{
    "_id" : ObjectId("540d427e132c1f13547188cc"),
    "body" : "empty_post",
    "permalink" : "cxzdzjkztkqraoqlgcru",
    "author" : "machine",
    "title" : "US Constitution",
    "tags" : [
        "january",
        "mine",
        "modem",
        "literature",
        "saudi arabia",
        "rate",
        "package",
        "respect",
        "bike",
        "cheetah"
    ],
    "comments" : [
        {
            "body" : "empty_comment",
            "email" : "eAYtQPfz@kVZCJnev.com",
            "author" : "Kayce Kenyon"
        },.........

 

2) we need to count comments so we will unwind the comments first using

 {
        $unwind: "$comments"
    }

 

3) then we need to group comment as per author so we will add group query with it count using sum.

{
$group: {
"_id": "$comments.author",
"num_comments": {
$sum: 1
}
}
}

 4) then we will sort from max to min number of comments. so we will add 

{
        $sort: {
            "num_comments": 1
        }
    }


5) note: this is large data so we will add limit to 1 rows by using
{$limit: 1}

so your final query will be

db.posts.aggregate([
{
$project: {
"_id": 0,
"comments": 1
}
},
{
$unwind: "$comments"
},
{
$group: {
"_id": "$comments.author",
"num_comments": {
$sum: 1
}
}
},
{
$sort: {
"num_comments": 1
}
},
{
$limit: 1
}
]
};
AND ANSWER I GOT IS Gisela Levin

 

No comments:

Post a Comment