-1

I have a query that should return multiple subdocuments from an array in a document, based on a timestamp range criteria. I first choose the main documents by specifying some id's:

In the Mongo Shell it is:

 db.fps.find({"_id": {$in: [15,24] }}, {someArray: {$elemMatch: {Timestamp: {$gt: "2018-06-06T18:00:00", $lt:"2018-06-07"}}}}).pretty()

Because of $elemMatch, it returns only the first document that matches my query. However, I want all relevant documents returned that match the criteria.

How would I have to do the query in mongoose?

MMMM
  • 3,320
  • 8
  • 43
  • 80

1 Answers1

1

Let's say you have a document like this:

db.fps.save({_id: 15, someArray: [ { Timestamp: "2018-06-06T19:00:00" }, { Timestamp: "2018-06-06T19:00:00" }, { Timestamp: "2018-06-07T00:00:00" } ]});

To filter nested array you need aggregation framework, where $match will represent your matching condition and $filter will apply Timestamps comparison. $addFields simply overwrites someArray in result set here

db.fps.aggregate([
    {
        $match: { "_id": {$in: [15,24] } }
    },
    {
        $addFields: {
            someArray: {
                $filter: {
                    input: "$someArray",
                    as: "doc",
                    cond: {
                        $and: [
                            { $gt: [ "$$doc.Timestamp", "2018-06-06T18:00:00" ] },
                            { $lt: [ "$$doc.Timestamp", "2018-06-07" ] }
                        ]
                    }
                }
            }
        }
    }
])
mickl
  • 48,568
  • 9
  • 60
  • 89