Javier Cárdenas
Javier Cárdenas

Reputation: 4035

Mongo - Querying inside array

I have this db structure

{
"_id": 107,
"standard": {"name": "building",
               "item": [{"code": 151001,
                          "quantity": 10,
                          "delivered": 8,
                          "um": "kg" },
                          {"code": 151001,
                          "quantity": 20,
                          "delivered": 6,
                          "um": "kg" }]
              }
}

And i would like to find all the objects that have code:151001 and just show the delivered field.

For example it would show something like this:

{delivered: 8}
{delivered: 6}

So far i got this query, but it does not show exactly what i want:

db.test.find(
        {
            "standard.item.code": 151001
        }
        ).pretty()

Upvotes: 0

Views: 94

Answers (1)

Stennie
Stennie

Reputation: 65303

Since your items are in an array, your best approach will be to use the Aggregation Framework for this.

Example code:

db.test.aggregate(
    // Find matching documents (could take advantage of an index)
    { $match: {
        "standard.item.code" : 151001,
    }},

    // Unpack the item array into a stream of documents
    { $unwind: "$standard.item" },

    // Filter to the items that match the code
    { $match: {
        "standard.item.code" : 151001,
    }},

    // Only show the delivered amounts
    { $project: {
        _id: 0,
        delivered: "$standard.item.delivered"
    }}
)

Results:

{
    "result" : [
        {
            "delivered" : 8
        },
        {
            "delivered" : 6
        }
    ],
    "ok" : 1
}

You'll notice there are two $match steps in the aggregation. The first is to match the documents including that item code. After using $unwind on the array, the second $match limits to the items with that code.

Upvotes: 3

Related Questions