使用MongoDB模板进行嵌套搜索

时间:2017-05-09 16:51:12

标签: mongodb aggregation-framework spring-mongodb

我在Mongo DB中有下面的文档,我写了一个java代码来从最里面的元素获取数据。出于某种原因,它没有给我任何结果。

输入数据

{
"_id": "59036b0fa036cc28c8e07db6",
"srcName":"test1",
"sections": [{
    "_id": "8769669696",
    "data": [{
            "srcKey": "Bonds",
            "rowIdx": 0,
            "values": [{
                    "srcDesc": "Assets",
                    "valuesNumber": 10000
                },
                {
                    "srcDesc": "NonAssets",
                    "valuesNumber": 75500
                },
                {
                    "srcDesc": "liabilities",
                    "valuesNumber": 1566
                }
            ]
        },
        {
            "srcKey": "01",
            "rowIdx": 1,
            "values": [{
                "srcDesc": "NonAssets",
                "valuesNumber": 1566
            }]
        }
    ]
}]
}

我想要的结果是 从...中选择valuesNumber,其中srcName =“test1”AND srcKey =“Bonds”AND srcDesc =“Assets”

Java代码如下

 AggregationOperation match=Aggregation.match(Criteria.where("srcName").in("test1")
            .and("sections.data.values.srcDesc").in("Assets")
            .and("sections.data.srcKey").in("Bonds"));


    AggregationOperation unwind1=Aggregation.unwind("sections");
    AggregationOperation unwind2=Aggregation.unwind("sections.data");
    AggregationOperation unwind3=Aggregation.unwind("sections.data.values");

    Aggregation aggregation=Aggregation.newAggregation(match,unwind1,unwind2,unwind3,match);

    BasicDBObject basicDBObject=mongoTemplate.aggregate(aggregation,"InsStatData",BasicDBObject.class).getUniqueMappedResult();

1 个答案:

答案 0 :(得分:0)

它解决了我的问题。我只需要做一个正确的映射来获取Mapped结果。原始代码中没有。 - 刚刚编辑用户3516787