Shravya
Shravya

Reputation: 218

Getting the size of arraylist from a MongoDB table

I am trying to get the count of followers from user table which is basically a array list using java programming.

I am using below query to get the count using command line interface.

db.userinfo.aggregate([{ $project : {followersCount : {$size: "$followers"}}}])

But I am not able to create the same query in java as I am new. Below is the code I wrote in java and I am getting com.mongodb.MongoCommandException: Command failed with error 17124: 'The argument to $size must be an array, but was of type: int' Error.

AggregateIterable<Document> elements = collectionUserInfo.aggregate(
                Arrays.asList(new BasicDBObject("$project", new       BasicDBObject("followers",
                        new BasicDBObject("$size", new BasicDBObject("followers",1).put("followers",new BasicDBObject("$ifNull", "[]")))))));

Can Anyone please help me with this

Upvotes: 2

Views: 1743

Answers (2)

s7vr
s7vr

Reputation: 75954

You can try something like with Java 8 and Mongo Driver 3.x version. You should try not to use old type ( BasicDbObject) and where possible use api method.

List<Integer> followersCount = collectionUserInfo.aggregate(
            Arrays.asList(Aggregates.project(Projections.computed(
                    "followersCount",
                    Projections.computed("$size", "$followers"))
                    )
            ))
   .map(follower -> follower.getInteger("followersCount"))
   .into(new ArrayList<>());

Upvotes: 5

Shravya
Shravya

Reputation: 218

I tried this and it worked fine.

AggregateIterable<Document> elements = collectionUserInfo.aggregate(
                Arrays.asList(new BasicDBObject("$project", new BasicDBObject("followers",
                        new BasicDBObject("$size", "$followers")))));

Thanks

Upvotes: 1

Related Questions