Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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<>());
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!