我的藏品中有以下文件
/* 1 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef74722"),
"user_id" : "bcd001",
"age" : 45.0,
"status" : "A",
"date" : ISODate("2017-04-24T00:00:00.000Z")
}
...
/* 9 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef7472a"),
"user_id" : "bcd020",
"age" : 50.0,
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
/* 10 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef7472b"),
"user_id" : "bcd021",
"age" : 51.0,
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
我跳过了一些文件来缩短问题。
这是我的疑问:
db.getCollection('people').find({
date: {
$lte: ISODate('2017-04-24'),
$gte: ISODate('2017-04-24')
}
});
结果:
/* 1 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef74722"),
"user_id" : "bcd001",
"age" : 45.0,
"status" : "A",
"date" : ISODate("2017-04-24T00:00:00.000Z")
}
我想要的结果是:
/* 1 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef74722"),
"user_id" : "bcd001",
"age" : 45.0,
"status" : "A",
"date" : ISODate("2017-04-24T00:00:00.000Z")
}
/* 9 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef7472a"),
"user_id" : "bcd020",
"age" : 50.0,
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
/* 10 */
{
"_id" : ObjectId("58fe05f29b3b7a313ef7472b"),
"user_id" : "bcd021",
"age" : 51.0,
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
我有三个文档,其中包含日期'2017-04-24',但我只得到一个文档作为回应请帮助。
答案 0 :(得分:2)
您只需在结束日期添加一天,并使用$lt
作为结束日期。像这样:
db.getCollection('people').find({
date: {
$lt: ISODate('2017-04-25'),
$gte: ISODate('2017-04-24')
}
});
答案 1 :(得分:0)
可以使用聚合管道来完成:
阅读与此相关的官方mongodb文档https://docs.mongodb.com/manual/reference/operator/aggregation-date/
db.getCollection('people').aggregate(
[
{
$project:
{
year: { $year: "$date" },
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
user_id: 1,
age: 1,
status: 1,
date: 1
}
},
{
$match:
{
$and:
[
{day: 24},
{month: 04},
{year: 2017}
]
}
},
{
$project:
{
_id:1,user_id: 1,
age: 1,
status: 1,
date: 1
}
}
]
);
答案 2 :(得分:0)
另一个使用@veeram技术建议的答案,它与之前的答案相比较短,我不确定哪一个是有效的,但两者都有效。
db.getCollection('people').aggregate(
[
{
$project: {
ymd: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
user_id: 1,
age: 1,
status: 1,
date: 1
}
},
{
$match:{
ymd: "2017-04-24"
}
},
{
$project: {
user_id: 1,
age: 1,
status: 1,
date: 1
}
}
]
);