Mongo查询不适用于嵌入式文档

问题描述 投票:0回答:2

我正在使用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"
        },
        .........
        ..........
        .........
}
mongodb spring-data-mongodb
2个回答
0
投票
db.getCollection('employee').find({"departments":{"status" : "A"}})

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()));
© www.soinside.com 2019 - 2024. All rights reserved.