使用MongoTemplate聚合过滤MongoDB中的嵌套元素
我正在尝试筛选标题与给定输入标题数组匹配的字段数组,并显示完整的文档,不包括不匹配的字段。下面是我的文档。实际上,我想使用MongoTemplate实现这一点,但首先我尝试通过mongo查询来获得它。以下是我的文件:使用MongoTemplate聚合过滤MongoDB中的嵌套元素,mongodb,spring-boot,aggregation-framework,mongotemplate,Mongodb,Spring Boot,Aggregation Framework,Mongotemplate,我正在尝试筛选标题与给定输入标题数组匹配的字段数组,并显示完整的文档,不包括不匹配的字段。下面是我的文档。实际上,我想使用MongoTemplate实现这一点,但首先我尝试通过mongo查询来获得它。以下是我的文件: { "version": 2, "pageName": "Content_2", "domain": "bingo.com", "locale": "en-us", "contents": [ { "c
{
"version": 2,
"pageName": "Content_2",
"domain": "bingo.com",
"locale": "en-us",
"contents": [
{
"contentName": "Template_2",
"fields": [
{
"fieldType": "Plain Text",
"id": "companyName456",
"title": "Company Name",
"alternateText": "Company Name",
"value": "Microsoft",
"placeholder": "Enter your Company name"
},
{
"fieldType": "Plain Text",
"id": "designation789",
"title": "Designation",
"alternateText": "Designation",
"value": "Software Engineer",
"placeholder": "Enter your designation name"
}
]
}
]
}
我尝试了以下查询,但返回的结果为空:
db.contents.aggregate(
[
{ $match: { locale: "en-us" } },
{
$redact: {
$cond: {
if: { $in: [ "$title", ["Designation"] ] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
);
我期待以下结果:
{
"pageName": "Home",
"link": "hello.com",
"locale": "en-us",
"contents": [
{
"contentName": "Template_2",
"fields": [
{
"fieldType": "Plain Text",
"id": "designation789",
"title": "Designation",
"alternateText": "Designation",
"value": "Software Engineer",
"placeholder": "Enter your designation name"
}
]
}
]
}
请导游。我对MongoDB很陌生 这样的方法应该行得通
db.contents.aggregate([
# Match that local
{$match: { locale: "en-us" } },
# Unwind by contents and contents.fields
{$unwind: "$contents"},
{$unwind: "$contents.fields"},
# Match them
{$match: { "contents.fields.title": "Designation" } },
# group back by _id of the document
{$group: {
"_id": "$_id",
"contents": { "$push": "$contents" }
}}
])
如果您需要所有其他字段,也可以按如下方式分组
db.contents.aggregate([
{$match: { locale: "en-us" } },
{$unwind: "$contents"},
{$unwind: "$contents.fields"},
{$match: { "contents.fields.title": "Designation" } },
{$group: {
"_id": {
"_id": "$_id",
"version": "$version",
"pageName": "$pageName",
"domain": "$domain",
"locale": "$locale",
},
"contents": { "$push": "$contents" }
}},
{$project: {"version": "$_id.version",
"_id": "$_id._id",
"pageName": "$_id.pageName",
"locale": "$_id.locale",
"domain": "$_id.domain",
"contents": "$contents",}}
])
谢谢它帮助了我。在$project内部,是否有较短的方式来投影所有外部字段?我已经尝试过这种方法,但我正在寻找一个较短的解决方案。据我所知,但我也是mongoI的新手,我能够通过以下查询实现我的结果:
db.contents.aggregate([{$match:{pageName:{Content_2}},{$unwind:$contents},{$unwind:$contents.fields},{$match:{“contents.fields.title”:{$in:[“公司名称”]}}},{$group:{“{U id”:“$\U id”,“内容”:“{$push”:“$contents”},{$first:$$root”}},{$replaceRoot:{newRoot:{$mergeObjects:[“$root”,“{contents:'$contents''.$contents'}}}}}}}},{$code>