我正在使用Spring Data Mongo
和简单的mongo查询来获取“活动状态”部门的列表。
当我在下面的查询中使用时,它仍然也拉InActive
记录。
db.getCollection('employee').find({"departments.status" : "A"})
样本数据-
{
"firstName" : "Sichita",
"lastName" : "Vinchurkar",
"email" : "[email protected]",
"departments" : [
{
"deptName" : "IT Support",
.......
.......
"status" : "A"
},
{
"deptName" : "Mobile Development",
.......
.......
"status" : "I"
},
{
"deptName" : "Advisory Dept",
.......
.......
"status" : "A"
},
.........
..........
.........
}
db.getCollection('employee').find({"departments":{"status" : "A"}})
该解决方案正在通过MongoDB Spring Data(v2.2.6)MongoTemplate
API使用聚合。您无法使用find
查询(因此使用聚合的$filter
数组运算符)来基于条件检索特定的数组元素。
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
Aggregation agg = newAggregation(
match(Criteria.where("departments.status").is("A")),
project()
.and(filter("departments")
.as("dept")
.by(Eq.valueOf("dept.status").equalToValue("A")))
.as("departments")
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "collection", Document.class);
results.forEach(doc -> System.out.println(doc.toJson()));