我在mongodb中有一个集合,其中字段嵌套在语言根目录下:
{
en: {
title: "eng title",
content: "eng content",
},
it: {
title: "it title",
content: "it content"
}
//common attributes for all languages
images: {
mainImage: "dataURL",
thumbImage: "dataURL"
}
}
我有一个名为'currentLang'的变量;我需要通过标题找到一个文档,只选择“currentLang”对象和公共字段(本例中的图像); 但对于“currentLang”对象,我希望输出文档不嵌套;例如,拥有currentLang =“en”
期望的输出:
{
title: "eng title",
content: "eng content",
images: {
mainImage: "dataURL",
thumbImage: "dataURL"
}
}
这可能吗?
答案 0 :(得分:3)
您需要汇总如下:
find
对象,仅匹配包含($exists)语言的记录。Projection
对象来投影字段。代码:
var currentLang = "en";
var project = {};
project["title"] = "$"+currentLang+".title";
project["content"] = "$"+currentLang+".content";
project["images"] = 1;
var find = {};
find[currentLang] = {"$exists":true};
db.collection.aggregate([
{$match:find},
{$project:project}
])
答案 1 :(得分:2)
我不确定你是如何查询的,所以我假设你直接通过mongo客户端。假设您已定义变量
>currentLang = "en";
您可以运行aggregation operation并使用$project operator重新构建文档的演示文稿。
以下是我测试过的一个例子:
> db.test.aggregate({$project:
{_id: 0,
title: "$" + currentLang + ".title",
content: "$" + currentLang + ".content",
images: 1
}
}).pretty();
{
"images" : {
"mainImage" : "dataURL",
"thumbImage" : "dataURL"
},
"title" : "eng title",
"content" : "eng content"
}
如果您想将其与实际查询结合使用,则可以将其包含为$match operator,例如:
> db.test.aggregate(
{$match:
{"en.title": "eng title"}
},
{$project:
{_id: 0,
title: "$" + currentLang + ".title",
content: "$" + currentLang + ".content",
images: 1
}
}).pretty();