我正在尝试从用户表中获取关注者的数量,该用户表基本上是使用Java编程的数组列表。
我正在使用下面的查询来获取使用命令行界面的计数。
db.userinfo.aggregate([{ $project : {followersCount : {$size: "$followers"}}}])
但是我无法像我新创建的那样在Java中创建相同的查询。以下是我在Java中编写的代码,并且正在获取com.mongodb.MongoCommandException:命令失败,错误17124:'$ size的参数必须是数组,但类型为: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<>());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句