Joe
Joe

Reputation: 4254

Mongoose, filter subdocument array by date

[{
    "_id" : ObjectId("5f3d0f13fd6fd6667f8f56d6"),
    "name" : "A",
    "prices" : [ 
        {
            "_id" : ObjectId("5f3d0f16fd6fd6667f8f57fb"),
            "d" : ISODate("2019-08-19T00:00:00.000Z"),
            "h" : 182.1,
        }, 
        {
            "_id" : ObjectId("5f3d0f16fd6fd6667f8f57fc"),
            "d" : ISODate("2019-08-20T00:00:00.000Z"),
            "h" : 182.1,
        },
        {
            "_id" : ObjectId("5f3d0f16fd6fd6667f81f57fc"),
            "d" : ISODate("2019-08-21T00:00:00.000Z"),
            "h" : 182.1,
        }
   ]
}]

Input:

from: '2019-08-20'
to: '2019-08-21'

Exepected output

[{
        "_id" : ObjectId("5f3d0f13fd6fd6667f8f56d6"),
        "name" : "A",
        "prices" : [ 
            {
                "_id" : ObjectId("5f3d0f16fd6fd6667f8f57fc"),
                "d" : ISODate("2019-08-20T00:00:00.000Z"),
                "h" : 182.1,
            },
            {
                "_id" : ObjectId("5f3d0f16fd6fd6667f81f57fc"),
                "d" : ISODate("2019-08-21T00:00:00.000Z"),
                "h" : 182.1,
            }
       ]
    }]

So I want to filter prices array so it only returns items within the given date range based on variable d

So some form of aggregation.

mongoose.model("stock").aggregate(...)

Some combination of $unwind $filter, $gte, $gle

Upvotes: 0

Views: 198

Answers (1)

Gibbs
Gibbs

Reputation: 22964

You can do as below

db.collection.aggregate([
  {
    $project: {
      items: {
        $filter: {
          input: "$prices",
          as: "price",
          cond: {
            "$and": [//only date conditions
              {
                $gte: [
                  "$$price.d",
                  new Date("2019-08-20")
                ]
              },
              {
                $lte: [
                  "$$price.d",
                  new Date("2019-08-21")
                ]
              }
            ]
          }
        }
      }
    }
  }
])

play

Upvotes: 2

Related Questions