使用聚合操作过滤深度嵌套的列表Spring数据

时间:2019-01-24 19:04:34

标签: mongodb spring-boot spring-data aggregation-framework mongotemplate

我有以下文件

undefined is not an object (evaluating 't.SHORT')

我正在根据域,语言环境和contentName过滤数据。至此,一切正常。现在,在fields数组内部,我只想显示标题与特定值匹配的那些字段。我无法弄清楚如何通过聚合操作做到这一点。我已经尝试了以下代码段:

import Toast from 'react-native-simple-toast';

它将所有属性返回为null。请指导。我是MongoDB的新手。预先感谢;

1 个答案:

答案 0 :(得分:0)

您可以使用此 Aggregation

db.collection.aggregate([
        { $unwind: '$contents' },
        { $match: { "locale": "en-us", 
"domain": "bingo.com", "contents.contentName": "Template_2"} },
        { $unwind: '$contents.fields' },
        { $match: { 'contents.fields.title' : "Company Name" } },
        { $group: { _id: '$_id', 
              fields: { $push: { title: '$contents.fields.title'}}, 
              "locale" : {$first: "$locale"},
              "domain" : {$first: "$domain"},
              "pageName" : {$first: "$pageName"},
              'contentName': {$first: '$contents.contentName'}
              }
        },
        { $group: { _id: '$_id', 
         "locale" : {$first: "$locale"},
         "domain" : {$first: "$domain"},
         "pageName" : {$first: "$pageName"},
         contents: { $push: { "contentName": '$contentName', "fields": '$fields' }}, 
        }}
    ])

或者简单地应用它。我的道歉如果我对语法有误,但要尽力使它们正确

Aggregation aggregation = newAggregation(
                    unwind("contents),
                    match(
                         where("$domain").is(domain)
                        .and("$contents.contentName").is(templateName)
                        .and("$locale").in(criteria.getLocales())
                       ),
                    unwind("$contents.fields"),
                    match(where("$contents.fields.title").is(title)),
                    group("_id")
                     .push("$contents.fields.title").as("fields")
                     .push("$locale").as("locale")
                     .push("$domain").as("domain")
                     .push("$pageName").as("pageName")
                     .push("$contents.contentName").as("contentName"),
                 group("_id")
                 .push("locale").as("locale")
                 .push("domain").as("domain")
                 .push("pageName").as("pageName")
                 .push(new BasicDBObject
                   ("contentName", "$contentName").append
                   ("fields", "$fields").as("contents"))
                );
AggregationResults<MyClass> list = mongoOperations.aggregate(aggregation, MyClass.class,
                MyClass.class);

运行它,结果正在等待您...

相关问题