在mongo db中选择嵌套字段 [英] Select nested fields in mongo db

查看:55
本文介绍了在mongo db中选择嵌套字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb中有一个集合,其中字段嵌套在语言根目录下:

I have a collection in mongodb where fields are nested under a language root:

{
    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"

I have a variable called 'currentLang'; I need to find a document by title selecting only the "currentLang" object and the common fields (images in this example); but for the "currentLang" object, I would like to have the output document not nested; for example, having currentLang = "en"

所需的输出:

{
    title: "eng title",
    content: "eng content",
    images: {
        mainImage: "dataURL",
        thumbImage: "dataURL"
    }
}

这可能吗?

推荐答案

您需要进行以下汇总:

  • 构造一个find对象,使其仅匹配包含以下内容的记录( $ exists )的语言.
  • 构造一个Projection对象以投影字段.
  • Construct a find object to match only the records containing($exists) the language.
  • Construct a Projection object to project the fields.

代码:

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}
])

这篇关于在mongo db中选择嵌套字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆