0

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()
2
  • 1
    Better use aggregation framework with $unwind, $project and $match Commented Jan 4, 2014 at 20:02
  • Could you give me an example? Commented Jan 4, 2014 at 20:28

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.