Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java Springdata Mongo中的mongodb Mongo DB请求

我在文件里有一个数组

{
    "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。聚合(聚合,“CustmObjects”,Object.class)

我也试着用{},我用了这个答案

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) 个答案

  1. # 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);