我想计算type="User.Notice"
所在的子文档的数量。我的数据库如下。
我写了以下查询,但它总是返回1或0。它可能有什么问题。
long countss = eventlist.count(new BasicDBObject("192_168_10_17.type", new BasicDBObject("$eq", "User.Notice")));
System.out.println(countss);
更新
如何获取特定数组下的所有记录。我想要所有文件在数组`192_168_10_17下。你能建议一个方法吗?
答案 0 :(得分:3)
首先,您应该展开192_168_10_17
并使用mongo聚合,如下所示
db.collectionName.aggregate({
"$unwind": "$192_168_10_17"
}, {
"$match": {
"192_168_10_17.type": "User.Notice"
}
}, {
"$group": {
"_id": "$192_168_10_17.type",
"count": {
"$sum": 1
}
}
}, {
"$project": {
"_id": 0,
"count": "$count"
}
})
以上查询返回所有匹配的User.Notice
计数。现在使用mongo java aggregation在java中转换此查询。我尝试了如下的java代码
// unwind 192_168_10_17
DBObject unwind = new BasicDBObject("$unwind", "$192_168_10_17");
// create pipeline operations, with the $match
DBObject match = new BasicDBObject("$match",new BasicDBObject("192_168_10_17.type", "User.Notice"));
// Now the $group operation
DBObject groupFields = new BasicDBObject("_id", "$192_168_10_17.type");
groupFields.put("count", new BasicDBObject("$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields);
// build the $projection operation
DBObject fields = new BasicDBObject("_id", 0);
fields.put("count", "$count");
DBObject project = new BasicDBObject("$project", fields);
// run aggregation
List < DBObject > pipeline = Arrays.asList(match, group, project);
AggregationOutput output = collectionName.aggregate(pipeline);
for (DBObject result: output.results()) {
System.out.println(result);
}