Java Spring-data Mongo中的Mongo DB请求

时间:2019-03-05 23:27:55

标签: java mongodb spring-data-mongodb

我在文档内部有一个数组。

{
    "id" : "id_1",
    "name" : "name_1";
    "additionalData" : [
        {
             "additionalDataId" : "id_1_1",
             "additionalDataName" : "name_1_1",
             "longText" : "A long story about..."  
        },
        {
             "additionalDataId" : "id_1_2",
             "additionalDataName" : "name_1_2",
             "longText" : "A longer story about danger..."  
        },
        {
             "additionalDataId" : "id_1_3",
             "additionalDataName" : "name_1_3",
             "longText" : "A longer story about danger and courage"  
        },
    ]       
}

要检索名称为"name_1_2"的数组元素,请使用mongo查询。

db.collection.find( { name: "name_1"},
        { _id: 0, additionalData: { $elemMatch: { "additionalDataName": "name_1_2" } } 
    })

如何使用mongoTemplate执行相同操作?

我尝试过

Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.match(
            Criteria.where("name").is("name_1").and("additionalData.additionalDataName").is("name_1_2")
        ),
    Aggregation.project("additionalData"),

); mongoTemplate.aggregate(aggregation,“ CustmObjects”,Object.class);

我也尝试使用ArrayOperators.Filter.filter,我用了这个答案。

Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.match(Criteria.where("name").is("name_1")),
        Aggregation.project("additionalData").and(
                ArrayOperators.Filter.filter("additionalData").as("item")
                        .by(ComparisonOperators.valueOf("item.additionalDataName").equalTo("name_1_2"))
        )
    );
mongoTemplate.aggregate(aggregation, "CustmObjects", Object.class);

https://stackoverflow.com/a/46769125/4587961

无论如何,我得到的结果是数组的所有元素。 请帮忙!

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,这将提供所需的结果。

Query query = new Query(new Criteria().andOperator(
    Criteria.where("name").is("name_1"),
    Criteria.where("additionalData.additionalDataName").is("name_1_2")
));
query.fields().include("additionalData").exclude("_id");

List<Document> results = template.find(query, collectionName, org.bson.Document.class);