anilthapliyal
anilthapliyal

Reputation: 105

Find the average of array element in MongoDB using java

I am new to MongoDB. I have to find the average of array element in Mongo DB e.g

{
"_id" : ObjectId("51236fbc3004f02f87c62e8e"),
"query" : "iPad",
"rating" : [
    {
        "end" : "130",
        "inq" : "403",
        "executionTime" : "2013-02-19T12:27:40Z"
    },
    {
        "end" : "152",
        "inq" : "123",
        "executionTime" : "2013-02-19T12:35:28Z"
    }
]
}

I want the average of "inq" where query:iPad

Here the output should be:

inq=263

I searched in google and got the aggregate method but not able to convert it in java code.

Thanks in advance

Regards

Upvotes: 1

Views: 2650

Answers (2)

anilthapliyal
anilthapliyal

Reputation: 105

Let's try to decompose that problem. I would start with:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0,
q:"$query",i:"$rating.inq"}})

The projection is not required but makes the rest a little bit more readable:

{
    "result" : [
            {
                    "q" : "iPad",
                    "i" : "403"
            },
            {
                    "q" : "iPad",
                    "i" : "123"
            }
    ],
    "ok" : 1
}

So how do I group that? Of course, by "$q":

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0, 
q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q"}}) :

{ "result" : [ { "_id" : "iPad" } ], "ok" : 1 }

Now let's add some aggregation operators:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0, q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q", max: {$max: "$i"}, min: {$min: "$i"}}}) :

{
    "result" : [
            {
                    "_id" : "iPad",
                    "max" : "403",
                    "min" : "123"
            }
    ],
    "ok" : 1
}

Now comes the average:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project:  
{_id:0,q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q", av: {$avg:"$i"}}});

Upvotes: 4

ritesh
ritesh

Reputation: 917

Try to get the java drivers for mongodb. I am able to get this link from mongodb site. Please check this: http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/#java-driver-and-aggregation-framework

Upvotes: 0

Related Questions