我最近遇到了同样的问题,我想添加一些额外的信息。
您可以通过两种方式插入日期:
- 在 nodejs 服务器端创建(例如在 ExpressJS 脚本中)
示例:插入一个新对象并为其添加时间戳
db.collection('mycollection').findOneAndUpdate({'name': req.body.name}, {
// only "update" if it's an insert, meaning name is not found
$setOnInsert: {
'name': req.body.name,
'date_added': new Date()
}
}, {
upsert: true
}, (err, result) => {
if(err) return res.send(err);
res.send(result);
});
- 在客户端从 JS 创建,然后通过 POST 请求使用 JSON 对象中的 REST API 通过网络发送
例子:
// Send POST Request here
fetch('addDate', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'date_added': new Date()
})
})
对于 1. 和 2.,您可以使用new Date('2014-01-22T14:56:59.301Z')
上述答案中所述的函数创建日期
。不同之处在于,如果您像 1. 那样在服务器端使用 MongoClient 包进行操作,则它会存储为ISODate('2014-01-22T14:56:59.301Z')
MongoDB 中的 a。如果您按照 2. 中的方式进行操作,则在客户端将其存储为 String:'2014-01-22T14:56:59.301Z'
在 MongoDB 中。
要查询您需要使用的 ISODate 对象new Date('2014-01-22T14:56:59.301Z')
或ISODate('2014-01-22T14:56:59.301Z')
要查询您只使用字符串的字符串:'2014-01-22T14:56:59.301Z'
以下是一些使用 mongo shell 的查询示例:
存储为字符串的日期:
db.mycollection.findOne({date_added {$gte:'2018-06-22T00:07:53.688Z'}})
这返回
{
"_id" : ObjectId("5b2c3dd90078ce3cd484ef21"),
"name" : "alfons",
"date_added" : "2018-06-22T00:07:53.688Z"
}
存储为 ISODate 的日期:
db.mycollection.findOne({date_added: {$lte: ISODate('2018-06-26T23:24:37.023Z')}})
或改用“新日期”:
db.mycollection.findOne({date_added: {$lte: new Date('2018-06-26T23:24:37.023Z')}
这将返回:
{
"_id" : ObjectId("5b2bb21e1954b104e61ff735"),
"name" : "ceasar",
"date_added" : ISODate("2018-06-21T14:11:41.323Z")
}