我正在尝试从用户表中获取关注者的数量,该表基本上是一个使用 Java 编程的数组列表。
我正在使用以下查询通过命令行界面获取计数。
db.userinfo.aggregate([{ $project : {followersCount : {$size: "$followers"}}}])
但我无法在 java 中创建与我新手相同的查询。下面是我用 java 编写的代码,我收到 com.mongodb.MongoCommandException: Command failed with error 17124: 'The argument to $size must be an array, but was of type: int' 错误。
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", "[]")))))));
谁能帮我解决这个问题
最佳答案
您可以尝试使用 Java 8 和 Mongo Driver 3.x 版本。您应该尽量不要使用旧类型 (BasicDbObject
),并尽可能使用 api 方法。
List<Integer> followersCount = collectionUserInfo.aggregate(
Arrays.asList(Aggregates.project(Projections.computed(
"followersCount",
Projections.computed("$size", "$followers"))
)
))
.map(follower -> follower.getInteger("followersCount"))
.into(new ArrayList<>());
关于java - 从 MongoDB 表中获取数组列表的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41559457/