如何将以下查询转换为Mongo Java驱动程序的Java代码?
db.post.aggregate(
[
{ $match : {"name" :{'$in': ["michael", "jordan"] } }},
{ $group : { _id : "$game.id" , count : { $sum : 1 } } }
]
)
我的功能不起作用:
DBObject match = new BasicDBObject('$match', new BasicDBObject("name", names));
答案 0 :(得分:1)
$in
运算符接受参数的数组或列表,因此任何列表基本上都会这样做。但是你需要形成相应的BSON。缩进代码有助于可视化:
BasicDBList inArgs = new BasicDBList();
inArgs.add("michael");
inArgs.add("jordan");
DBObject match = new BasicDBObject("$match",
new BasicDBObject("name",
new BasicDBObject("$in", inArgs )
)
);
DBObject group = new BasicDBObject("$group",
new BasicDBObject("_id","$game.id").append(
"count", new BasicDBObject("$sum",1)
)
);
答案 1 :(得分:0)
根据Aggregation Documentation,您的查询应如下所示:
DBObject match = new BasicDBObject('$match', new BasicDBObject('name', new BasicDBObject('$in', names)));