0

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

1 Answer 1

1

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

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

2 Comments

Thank you, it helped me! And how can I add another condition, for example, Data >= 2017-12-31?
Use $and to add multiple conditions into cond. Check this example

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.