collection : {
"_id" : ObjectId("5ab7757d3295a10bac3ad927"),
"resource_id" : "msh",
"resource_name" : "m",
"projects" : [
{
"project_id" : "ABC",
"project_name" : "test1",
"allocation" : [
{
"month_fte" : 0.4,
"month" : ISODate("2018-01-01T00:00:00.000+0000")
},
{
"month_fte" : 0.2,
"month" : ISODate("2018-02-01T00:00:00.000+0000")
},
{
"month_fte" : 0.9,
"month" : ISODate("2018-03-01T00:00:00.000+0000")
}
]
},
{
"project_id" : "XYZ",
"project_name" : "test2",
"allocation" : [
{
"month_fte" : 0.1,
"month" : ISODate("2018-01-01T00:00:00.000+0000")
},
{
"month_fte" : 0.5,
"month" : ISODate("2018-02-01T00:00:00.000+0000")
},
{
"month_fte" : 0.4,
"month" : ISODate("2018-03-01T00:00:00.000+0000")
},
{
"month_fte" : 0.4,
"month" : ISODate("2018-04-01T00:00:00.000+0000")
}
]
}
] } {
"_id" : ObjectId("5ab7757d3295a10bac3ad928"),
"resource_id" : "rp",
"resource_name" : "r",
"projects" : [
{
"project_id" : "8P0CHF",
"project_name" : "test1",
"allocation" : [
{
"month_fte" : 1.0,
"month" : ISODate("2018-01-01T00:00:00.000+0000")
},
{
"month_fte" : 0.5,
"month" : ISODate("2018-02-01T00:00:00.000+0000")
},
{
"month_fte" : 0.3,
"month" : ISODate("2018-03-01T00:00:00.000+0000")
}
]
},
{
"project_id" : "8P0ABC",
"project_name" : "test3",
"allocation" : [
{
"month_fte" : 0.1,
"month" : ISODate("2018-04-01T00:00:00.000+0000")
},
{
"month_fte" : 0.5,
"month" : ISODate("2018-05-01T00:00:00.000+0000")
},
{
"month_fte" : 0.4,
"month" : ISODate("2018-06-01T00:00:00.000+0000")
}
]
}
] }
查询:
db.resource.find({
$and: [
{ 'projects.allocation.month' : { $gt: ISODate("2018-01-01T00:00:00.000+0000") } },
{ 'projects.allocation.month': { $lt: ISODate("2018-03-01T00:00:00.000+0000") } }
]
})
输出:
{
"_id" : ObjectId("5ab7757d3295a10bac3ad927"),
"resource_id" : "mshirgir",
"resource_name" : "manoj shirgire",
"projects" : [
{
"project_id" : "8P0CHF",
"project_name" : "test1",
"allocation" : [
{
"month_fte" : 0.4,
"month" : ISODate("2018-01-01T00:00:00.000+0000")
},
{
"month_fte" : 0.2,
"month" : ISODate("2018-02-01T00:00:00.000+0000")
},
{
"month_fte" : 0.9,
"month" : ISODate("2018-03-01T00:00:00.000+0000")
}
]
},
{
"project_id" : "8P0XYZ",
"project_name" : "test2",
"allocation" : [
{
"month_fte" : 0.1,
"month" : ISODate("2018-01-01T00:00:00.000+0000")
},
{
"month_fte" : 0.5,
"month" : ISODate("2018-02-01T00:00:00.000+0000")
},
{
"month_fte" : 0.4,
"month" : ISODate("2018-03-01T00:00:00.000+0000")
},
{
"month_fte" : 0.4,
"month" : ISODate("2018-04-01T00:00:00.000+0000")
}
]
}
] }
但获得所有分配,如何获得日期条件的分配
答案 0 :(得分:0)
您收到的结果是因为如果allocation
中的任何一个与您的查询匹配,mongodb会返回整个文档。
如果您想获得 ONLY 匹配的分配,您必须首先解开分配数组。
db.resource.aggregate([
{
{
$unwind: "$projects.allocation"
},
},
{
$match: {
$and: [
{ 'projects.allocation.month' : { $gt: ISODate("2018-01-01T00:00:00.000+0000") } },
{ 'projects.allocation.month': { $lt: ISODate("2018-03-01T00:00:00.000+0000") } }
]
}
}
])