Home > Software engineering >  How can I get multiple elements from an array in MongoDB?
How can I get multiple elements from an array in MongoDB?

Time:11-14

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"
            },
            ...
            ]

CodePudding user response:

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

  • Related