Is it possible not to publish specific array elements?

I have documents like below that represent languages. Language names are stored in nested array. Is there a way to publish only one translation? I mean I’d like to publish only English translation.

{
    "_id" : "kxcNH3HBQptYD6Y7p",
    "code" : "en",
    "name" : [ 
        {
            "lang" : "kxcNH3HBQptYD6Y7p",
            "name" : "English",
            "lowerName" : "english"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7q",
            "name" : "Anglais",
            "lowerName" : "anglais"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7r",
            "name" : "Englisch",
            "lowerName" : "englisch"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7s",
            "name" : "Inglés",
            "lowerName" : "inglés"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7t",
            "name" : "英語",
            "lowerName" : "英語"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7u",
            "name" : "Inglese",
            "lowerName" : "inglese"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7w",
            "name" : "английский",
            "lowerName" : "английский"
        }, 
        {
            "lang" : "kxcNH3HBQptYD6Y7v",
            "name" : "Angielski",
            "lowerName" : "angielski"
        }
    ],
    "_md" : {
        "cd" : 1487586631521.0,
        "cb" : null
    }
}

Yes, you can use the $elemMatch operator :grinning:

var language = "kxcNH3HBQptYD6Y7p";
Collection.find({}, {fields:{name:{$elemMatch:{lang:language}}}});

https://docs.mongodb.com/v3.0/tutorial/project-fields-from-query-results/#projection-for-array-fields

1 Like

Thank you! I tried to find it in meteor docs but it’s indeed mongo feature!

Now I’m trying to invert this filter so that I could exclude some array elements but publish everything else. In other words I don’t want to write “code: 1” explicitly.

var language = "kxcNH3HBQptYD6Y7p";
Collection.find({}, {
    fields:{
        code: 1, // Don't want to enumerate all other equired fields here
        name: {
            $elemMatch: {
                lang:language
            }
        }
    }
});
1 Like

Hmm, I think you’re going to have to live with enumerating all fields.

Check Return All But the Excluded Field section: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/