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

How can I get multiple elements from an array in MongoDB?

How can I get multiple elements from an array at once that satisfy a specific condition, for example: Date <= 2020-12-31. I read about $elemMatch, but I can only get one specific element with it.

"someArray": [
            {
                "Date": "2021-09-30",
                "value": "6.62"
            },
            {
                "Date": "2020-12-31",
                "value": "8.67"
            },
            {
                "Date": "2019-12-31",
                "value": "12.81"
            },
            {
                "Date": "2018-12-31",
                "value": "13.82"
            },
            {
                "Date": "2017-12-31",
                "value": "13.83"
            },
            ...
            ]

>Solution :

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

You can use $filter in an aggregation query like this:

db.collection.aggregate([
  {
    "$project": {
      "someArray": {
        "$filter": {
          "input": "$someArray",
          "as": "a",
          "cond": {
            "$lte": [
              "$$a.Date",
              ISODate("2020-12-31")
            ]
          }
        }
      }
    }
  }
])

Example here

Note that you can use $project or $set (available since version 4.2): example or $addFields: example

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