Reputation: 43
My mongodb collection looks like this. Basically for each product_id, there are multiple documents to store the availability across various dates.
{
"_id" : ObjectId("5bf22a773d3999bca17d4a3d"),
"timestamp" : ISODate("2018-12-30T18:30:00.000Z"),
"product_id" : "1",
"available" : true
}
{
"_id" : ObjectId("5bf22a773d3999bca17d4a3d"),
"timestamp" : ISODate("2018-12-31T18:30:00.000Z"),
"product_id" : "1",
"available" : true
}
How should I query so that, given a date interval availability is true for all the dates in that interval.
Example: Date interval: 30-12-2018 To 31-12-2018 AND avalability: true should return 2 documents in this case, because availability is true on both these dates. Please help.
Upvotes: 1
Views: 416
Reputation: 88
You could do the following, return all querys that have availability true and then with that array check filter the dates with a .filter, so the dates that interest you are between to parameters date1 < dateYouWant < date2.
Then return the array with the dates that interest you.
This two links will help you.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
What you could also do is use filter({})
and in the query to search with the statements $gt
(greater than) and $lt
(less than) you'd put something like this:
`filter({ $and[{ date: {$gt: minimumDate }, {$lt: maximumDate}, {avaliability: true}] })`
and: https://docs.mongodb.com/manual/reference/operator/query/and/
gt: https://docs.mongodb.com/manual/reference/operator/query/gt/
lt: https://docs.mongodb.com/manual/reference/operator/query/lt/
The and operator makes sure that you get the objects that satisfy both conditions
Hope it helps!
Upvotes: 1
Reputation: 431
product_id
db.collection.find({timestamp:{$gte:ISODate("2018-12-30T00:00:00.000Z"),$lte:ISODate("2018-12-31T23:59:59.000Z")}, available:true})
With product_id
db.collection.find({timestamp:{$gte:ISODate("2018-12-30T00:00:00.000Z"),$lte:ISODate("2018-12-31T23:59:59.000Z")}, available:true, product_id:1})
https://docs.mongodb.com/manual/reference/operator/query/gte/
Upvotes: 0