我编写了一个MongoDB本机查询,该查询可以正常工作。我正在尝试编写等效于Spring数据的查询,但无法这样做。基本上,我想根据输入数组中提供的标题过滤掉字段数组。这是示例文档:
{
"domain":"diageotest.com",
"locale":"en-gb",
"pageName":"Content_1",
"contents":[
{
"contentName":"Template_1",
"fields":[
{
"id":"firstname",
"fieldType":"Plain Text",
"title":"First Name",
"value":"Pawan"
},
{
"id":"lastname",
"fieldType":"Plain Text",
"title":"Last Name",
"value":"Kumar"
}
]
}
],
"createdBy":"ag-KumarJog",
"createdDate":"Jan 23,2019",
"isDefaultLocale":true,
"modifiedBy":"ag-KumarJog",
"modifiedDate":"Jan 23,2019",
"version":1
}
以下是我的本机查询:
db.contents.aggregate([
{$match: { $and: [
{"domain": "diageotest.com"},
{"locale": {$in: ["en-in", "en-us"]}},
{"contents.contentName": "Template_1"}
]
}
},
{$unwind: "$contents"},
{$unwind: "$contents.fields"},
{$match: { "contents.fields.title": {$in: ["First Name"]}}},
{$group: { "_id": "$_id",
"contents": { "$push": "$contents"},
"root": {$first:"$$ROOT"} }},
{$replaceRoot:{newRoot:{$mergeObjects:["$root",{contents:'$contents'}]}}},
{$skip : 0},
{$limit : 5}
]);
在这里,在上面的查询中,如果我在数组中传递“名字”(条件为$),则输出JSON将仅包含标题为“名字”的字段。
在Java中,我尝试在下面尝试,但卡在替换根目录上:
MatchOperation matchOperation = this.matchByTemplateDomainAndLocales(domainName, templateName,
requestBody.getLocales());
// ---------------------------------------------------//
UnwindOperation unwindContents = unwind("$contents");
UnwindOperation unwindFields = unwind("$contents.fields");
MatchOperation matchFields = match(where("contents.fields.title").in(requestBody.getFields()));
GroupOperation groupOperation = group("id").push("$contents").as("contents").first("$$ROOT").as("root");
//ReplaceRootOperation replaceRootOperation = builder().withDocument()
// ---------------------------------------------------//
SortOperation sortOperation = sort(sort);
LimitOperation limitOperation = limit(requestBody.getLimit());
SkipOperation skipOperation = skip(requestBody.getSkip().longValue());
在替换接受数组并执行合并的root时,我找不到合适的方法。请帮助。
答案 0 :(得分:0)
如果您不想更改“内容”字段名称,可以使用:
ReplaceRootOperation operation = replaceRoot().withValueOf(ObjectOperators.valueOf("$root").mergeWith("$content"));
否则,不确定这是否是最干净的解决方案,但您可以这样创建它:
Map<String, String> fieldMapping = new HashMap<>();
fieldMapping.put("content", "$content");
ReplaceRootOperation operation = replaceRoot().withValueOf(ObjectOperators.valueOf("$root").mergeWith(fieldMapping));