如何在MongoDB中基于条件从数组中获取元素?
我是MongoDB的初学者,下面是我的示例文档:如何在MongoDB中基于条件从数组中获取元素?,mongodb,mongodb-query,aggregation-framework,pymongo-3.x,Mongodb,Mongodb Query,Aggregation Framework,Pymongo 3.x,我是MongoDB的初学者,下面是我的示例文档: { "plan_id" : "100", "schedule_plan_list" : [ { "date" : "01-05-2020", "time" : "9:00AM -10:00AM" }, { "date" : "02-05-2020", "time" : "10:00AM -11:00AM" }, { "da
{
"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"
}
]
}
我想根据给定日期**02-05-2020获取下5个元素**
我给定的查询获取仅匹配02-05-2020,但我想要02-05-2020,03-05-2020,…06-05-2020
因此,任何人都可以帮助我解决此问题,您可以尝试以下聚合查询:
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
]
}
}
})
测试:
参考:
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
]
}
}
})