3
{
  "array": [
    {
      "date1": "date1",
      "date2": "date2",
      "childArray": [
        {
          "date1": "date1",
          "date2": "date2",
          "childArray": [
            {
              "date1": "date1",
              "date2": "date2"
            }
          ]
        }
      ]
    }
  ]
}

I have document that is of the format above - I need to be able to query give a date and fetch all recursively here if the date falls between date1 and date2.

Could use a bit of help -- I've looked into aggregation and a way of potentially flattening this structure out via the aggregation and then applying the query but I haven't gotten anywhere with it.

This is a sample -- the childArray can be any number of layers deep, so need something recursive.

1 Answer 1

1

You can do this with a find and $or:

var date = ISODate("2020-08-12T23:45:00Z")
db.collection.find({
    $or: [
          {array: { $elemMatch:{
                date1: {$lte: date},
                date2: {$gte: date}
          }}},
          {"array.childArray": { $elemMatch:{
                date1: {$lte: date},
                date2: {$gte: date}
          }}},
          {"array.childArray.childArray": { $elemMatch:{
                date1: {$lte: date},
                date2: {$gte: date}
          }}}
    ]
})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Joe - updating my question -- it should state that I don't actually know how deep this childArray nesting can go, so I need some sort of recursive query.
The mongo query language doesn't do looping, branching, or recursion. A BSON object is limited to 16MB, so there is an upper limit on the possible nesting in the document. You could programmatically create an $or array like this that is thousands deep and query with that.
Another option I was thinking was that --- could we somehow flatten that array by using map or something --- then query that flattened array.. so take the children and children of children and move them into a single flat array, again that could be done programatically
There would need to be a match in the fields of each array for graphLookup. Neither the mongo query language or aggregation have an operator to recursively flatten and array. You could use $unwind repeatedly, but your query would still only handle up to a specific depth.

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.