Java Spring-data Mongo中的Mongo DB请求 [英] Mongo DB request in Java Spring-data Mongo

查看:121
本文介绍了Java Spring-data Mongo中的Mongo DB请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我要使用mongo查询来检索名称为"name_1_2"的数组元素.

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" } } 
    })

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

How to do the same using 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);

); mongoTemplate.aggregate(aggregation, "CustmObjects", Object.class);

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

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!

推荐答案

如果我正确地理解了这个问题,那么将会得到想要的结果.

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

这篇关于Java Spring-data Mongo中的Mongo DB请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆