3

I've got a list of objects with name value pairs in them and I can't figure out how to retrieve a value from an array where name is a certain value.

For instance:

    {
            "ordernumber" : "192915",
            "orderparameters" : {
                    "list" : [
                            {
                                    "composite" : null,
                                    "name" : "CURRENCY_CODE",
                                    "value" : "NOK",
                                    "type" : "String"
                            },
                            {
                                    "composite" : null,
                                    "name" : "NEED_CUSTOMS_DOCUMENT",
                                    "value" : "True",
                                    "type" : "Boolean"
                            }
              ]}
    }

Now I need to find the value of the item with

"name": "NEED_CUSTOMS_DOCUMENT"

so in this case

"value": "True"

I can list all the values with

 db.orders.aggregate({ $match: { ordernumber:'1234' } }, { $project: { 'orderparameters.list.name': 1 } }).pretty()

But then how to retrieve the value field from the index with that name?

The index could be different on every document so I cant simply query "orderparameters.list.1.value"

2 Answers 2

3

Refine your aggregate pipeline to include a another stage with a $filter operator and that allows you to filter the list on a given condition, something like the following:

db.orders.aggregate([
    { $match: { 
        ordernumber: "1234", 
        "orderparameters.list.name": "NEED_CUSTOMS_DOCUMENT" 
    } },
    { $project: {
       list: {
          $filter: {
              input: "$orderparameters.list",
              cond: { $eq: ["$$this.name", "NEED_CUSTOMS_DOCUMENT"] }
          }
       } 
    } },
    { $project: { values: "$list.value" } }
])
Sign up to request clarification or add additional context in comments.

Comments

1

There is an operator especially made for this

$elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

db.orders.aggregate({ $match: { 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } } })

db.orders.find({ 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.