[
{ "item": "journal", "qty": 25,"date":"1/1/2016", "status": "A" },
{ "item": "notebook", "qty": 50,"date":"10/1/2016", "status": "A" },
{ "item": "paper", "qty": 100,"date":"20/1/2016", "status": "D" },
{ "item": "planner", "qty": 75,"date":"1/2/2016", "status": "D" },
{ "item": "postcard", "qty": 45,"date":"10/2/2016", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"20/5/2016", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"30/7/2016", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"2/3/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"5/5/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"6/5/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"8/10/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"11/10/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"12/11/2017", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"4/3/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"5/6/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"6/7/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"7/7/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"17/11/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"19/12/2018", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"5/1/2019", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"7/1/2019", "status": "A" },
{ "item": "postcard", "qty": 45,"date":"14/3/2019", "status": "A" }
]
以上是我的数据库结构。
db.lichi.find({date: {$gte : '1/1/2016', $lt : '1/1/2019'}})
这是我要从数据库中获取数据的查询。
在数据库中,我有字符串格式的日期。 我正试图以上述方式获取信息,但没有用。
给出结果
{ "item": "journal", "qty": 25,"date":"1/1/2016", "status": "A" },
{ "item": "notebook", "qty": 50,"date":"10/1/2016", "status": "A" }
只有两个文档。
请看看。
答案 0 :(得分:1)
将日期存储为字符串不是最好的方法,因为在这种情况下,您必须比较字符串而不是日期。如果由于某种原因必须将date
保留为字符串,则可以使用$dateFromString在查询中将其转换,然后应用过滤条件:
db.lichi.aggregate([
{
$addFields: {
date: {
$dateFromString: {
dateString: "$date",
format: "%d/%m/%Y"
}
}
}
},
{
$match: {
date: { $gte: ISODate("2016-01-01T00:00:00Z"), $lt: ISODate("2019-01-01T00:00:00Z") }
}
}
])