Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select nested fields in mongo db

Tags:

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

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"

desired output:

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

Is this possible?

like image 561
Cereal Killer Avatar asked Dec 05 '14 22:12

Cereal Killer


1 Answers

You need to aggregate as below:

  • Construct a find object to match only the records containing($exists) the language.
  • Construct a Projection object to project the fields.

Code:

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}
])
like image 80
BatScream Avatar answered Nov 08 '22 22:11

BatScream