我正在使用Spring Data Mongo
和简单的mongo查询来获取“活动状态”部门的列表。
当我在下面的查询中使用该查询时,它仍然也提取InActive
条记录。
db.getCollection('employee').find({"departments.status" : "A"})
样本数据-
{
"firstName" : "Sichita",
"lastName" : "Vinchurkar",
"email" : "svinchurkar@gmail.com",
"departments" : [
{
"deptName" : "IT Support",
.......
.......
"status" : "A"
},
{
"deptName" : "Mobile Development",
.......
.......
"status" : "I"
},
{
"deptName" : "Advisory Dept",
.......
.......
"status" : "A"
},
.........
..........
.........
}
答案 0 :(得分:0)
db.getCollection('employee').find({"departments":{"status" : "A"}})
答案 1 :(得分:0)
该解决方案正在与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()));
[编辑添加]
包括用于代码中使用的类和接口的import
语句:
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import static org.springframework.data.mongodb.core.aggregation.ComparisonOperators.Eq;