当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Getting the total count of array list elements from all documents of a collection

问题描述:

enter image description hereI am trying to get the activity of my users in which I am trying to get the total followers and following of all users in my userinfo table.

I am using the below command line query to get that which is working fine and I am getting the total count.

db.userinfo.aggregate([

{ "$group": {

"_id": null,

"followersCount": {

"$sum": {

"$size": { $ifNull: [ "$followers", [] ] }

}

},

"followingCount": {

"$sum": {

"$size": { $ifNull: [ "$i_am_following", [] ] }

}

}

}}

])

But I am unable to replicate this using java programming. Can we write this query in java using BasicDBObjects or Is there any other way to do this?

Here is the sample data for a single user.

db.userinfo.insert (

{

"username" : "user1",

"useremail" : "[email protected]",

"password" : "password",

"firstname" : "firstname",

"lastname" : "lastname",

"dob" : "24-05-1992",

"followers" : [

{

"user" : "user2",

"from_date" : "2016-12-15 09:59:04"

},

{

"user" : "user3",

"from_date" : "2016-12-15 08:59:04"

}

],

"i_am_following" : [

{

"user" : "user2",

"from_date" : "2016-12-15 08:59:04"

},

{

"user" : "user3",

"from_date" : "2016-12-15 09:59:04"

}

]

})

网友答案:

You can try something like this.

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.computed;
import static java.util.Arrays.asList;
import static java.util.Collections.EMPTY_LIST;

Bson group = group(null,
    sum("followersCount", computed("$size",
        computed("$ifNull",
            asList("$followers", EMPTY_LIST)))),
    sum("followingCount", computed("$size",
        computed("$ifNull",
            asList("$i_am_following", EMPTY_LIST))))
);

AggregateIterable <Document> output = userinfo.aggregate(asList(group));
分享给朋友:
您可能感兴趣的文章:
随机阅读: