Mongo DB request in Java Spring-data Mongo

2020-04-21 08:33发布

问题:

I have an array inside of document.

{
    "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"  
        },
    ]       
}

To retrieve element of array with name "name_1_2", I use mongo query.

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

How to do the same using mongoTemplate?

I have tried

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);

And I also tried to use ArrayOperators.Filter.filter, I used this answer.

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

Anyway, the result I got, all elements of the array. Please, help!

回答1:

If I understood the question correctly, this will give the desired results.

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);