peter vries peter vries - 1 year ago 132
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" }) %}


but that doesn't give me anything back.

Answer Source

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", "":"id1"}) %}
{% for entry in document.entries %}
    {% if === "id1" %}
        {# display contents #}
    {% endif %}
{% endfor %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download