Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDb regex search in array objects

I have the following collection:

{
    "invoice": {
        "data": [{
                "name": "VOUCHERNUMBER",
                "value": "59302311"
            }, {
                "name": "VOUCHERDATE",
                "value": "2020-02-20"
            }
        ]
    }
},
{
    "invoice": {
        "data": [{
                "name": "VOUCHERNUMBER",
                "value": "59112389"
            }, {
                "name": "VOUCHERDATE",
                "value": "2020-02-20"
            }
        ]
    }
},
{
    "invoice": {
        "data": [{
                "name": "VOUCHERNUMBER",
                "value": "59302378"
            }, {
                "name": "VOUCHERDATE",
                "value": "2020-02-11"
            }
        ]
    }
}

My task is to build a query that find all invoices which invoicenumbers includes "11" (or any other substring).

So I built the following statement:
{"invoice.data.name": "VOUCHERNUMBER", "invoice.data.value": {$regex : "11"} }
I’m expecting a result of the first two objects, but because of the second value in the third object, mongodb returns me all three objects. Then I tried
{$and : [{"invoice.data.name": "VOUCHERNUMBER"}, {"invoice.data.value": {$regex : "11"}}]}
with the same result …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I’m running out of ideas. Is there a solution to search for the string only in the value field where the corresponding "name" field contains "VOUCHERNUMBER"?

>Solution :

You need $elemMatch.

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

db.collection.find({
  "invoice.data": {
    "$elemMatch": {
      "name": "VOUCHERNUMBER",
      "value": {
        $regex: "11"
      }
    }
  }
})

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading