peter vries peter vries - 2 months ago 10
Twig Question

Get the right value out of the right array-entry in MongoDB / Twig

I'm trying to get a value from an array inside a mongodb collection.

My db entries look like:

_id : "somerandomid"
page : "page1"
entries : [ {
id : "id1"
entry : "content"
}

{
id : "id2"
entry : "content2"
} ]


I want to match
page : "page1"
first, then find the right entry in the 'entries' array based on 'id', then display the 'content' of that entry.

I tried:
{% set rightentry = mydb.find({page : "page1", id : "id1" }) %}


{{rightentry.content}}


but that doesn't give me anything back.

Answer

You won't be able to retrieve only the subdocument that matches your query from MongoDB directly.

You'll want to iterate over the entries that are returned with your retrieved document to find the one that matches:

{% set document = mydb.find({page:"page1", "entries.id":"id1"}) %}
{% for entry in document.entries %}
    {% if entry.id === "id1" %}
        {# display contents #}
    {% endif %}
{% endfor %}
Comments