2

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

1
  • I tried this and it worked fine. Commented Jan 10, 2017 at 1:26

2 Answers 2

5

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<>());
Sign up to request clarification or add additional context in comments.

1 Comment

the above code worked for me only after adding $ in front of followers at new Docment("$size", "$followers").
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.