mongodb bson 命令 (我算是发现了,查询的key加不加引号都可以)
db.your_db.aggregate([
{
$match: {
"$and": [{
"companyAwards": {
"$elemMatch": {
$and: [{
"awardLevel": {
"$in": ["国家级","省部级"]
}
}]
}
}
}]
}
},
{
$group: {
"_id": null,
"total": {
"$sum": 1
}
}
}
])
Java Bson 查询方式
public long calculateTotal(List<String> levels) {
BasicDBObject allQueryObject = new BasicDBObject();
List<BasicDBObject> elemMathDBObjects = new ArrayList<>() ;
List<BasicDBObject> totalAndDBObjects = new ArrayList<>() ;
totalAndDBObjects.add(new BasicDBObject("awardLevel",new BasicDBObject("$in",levels)));
elemMathDBObjects.add(new BasicDBObject(new BasicDBObject("companyAwards",
new BasicDBObject(QueryOperators.ELEM_MATCH,new BasicDBObject("$and",totalAndDBObjects)))));
allQueryObject.put("$and", elemMathDBObjects);
Bson totalGroup = Aggregates.group("null"
,new BsonField("total",new BasicDBObject("$sum", 1))
);
List<Bson> totalBsonList = new ArrayList<>();
totalBsonList.add(Aggregates.match(allQueryObject));
totalBsonList.add(totalGroup);
AggregateIterable<Document> totalAgg = MongodbUtils.aggregate("your_db",totalBsonList);
MongoCursor<Document> totalIterable = totalAgg.iterator();
long total = 0 ;
if (totalIterable.hasNext()){
Document document = totalIterable.next();
total = document.getInteger("total");
}
return total ;
}
java spring 模板查询(未验证,因为用spring模板时,速度不如Bson方式,所以此处大致写了一下,没有运行)
public void method(List<String> levels) {
Aggregation aggregation = newAggregation(
match(Criteria.where("companyAwards").elemMatch(Criteria.where("awardLevel").in(levels))),
count().as("total")
);
AggregationResults<JSONObject> result = MongodbUtils.find(JSONObject.class,aggregation,"your_db");
respDto.setData(result.getMappedResults());
}
}