从MongoDB表中获取arraylist的大小
问题描述:
我想从用户表中获取关注者的数量,这基本上是使用java编程的数组列表。从MongoDB表中获取arraylist的大小
我正在使用下面的查询来使用命令行界面来计数。
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和蒙戈驱动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<>());
答
我想这和它工作得很好。
AggregateIterable<Document> elements = collectionUserInfo.aggregate(
Arrays.asList(new BasicDBObject("$project", new BasicDBObject("followers",
new BasicDBObject("$size", "$followers")))));
感谢
我试过这个,它工作正常。 – Shravya