Reputation: 147
I am the beginner in MongoDB & Here is my sample doc given below :
{
"plan_id" : "100",
"schedule_plan_list" : [
{
"date" : "01-05-2020",
"time" : "9:00AM -10:00AM"
},
{
"date" : "02-05-2020",
"time" : "10:00AM -11:00AM"
},
{
"date" : "03-05-2020",
"time" : "9:00AM -10:00AM"
},
{
"date" : "04-05-2020",
"time" : "9:30AM -10:30AM"
},
{
"date" : "05-05-2020",
"time" : "9:00AM -10:00AM"
},
{
"date" : "06-05-2020",
"time" : "9:00AM -10:00AM"
},
{
"date" : "07-05-2020",
"time" : "9:30AM -10:30AM"
},
{
"date" : "08-05-2020",
"time" : "4:00PM -5:00PM"
}
]
}
I want to get next 5 elements ** based on given date is **"02-05-2020"
My given query fetch only match "02-05-2020" but I want "02-05-2020","03-05-2020",.."06-05-2020"
db.getCollection('schedule_plans').find({"plan_id" : "100"},{_id:0,"schedule_plan_list": { "$elemMatch": { "date" : "02-05-2020"}}})
so anyone help me to solve this
Upvotes: 5
Views: 3978
Reputation: 17935
You can try below aggregation query :
db.collection.aggregate([
{ $match: { "plan_id": "100" } },
/** You can re-create `schedule_plan_list` field with condition applied & slice the new array to keep required no.of elements in array */
{
$project: {
_id: 0,
"schedule_plan_list": {
$slice: [
{
$filter: { input: "$schedule_plan_list", cond: { $gte: [ "$$this.date", "02-05-2020" ] } }
},
5
]
}
}
})
Test : mongoplayground
Ref : aggregation
Upvotes: 5