如何在MongoDB中插入带有日期的文档?
要在MongoDB中插入带有日期的文档,请使用Date()
。以下是语法
“yourFieldName”:new Date(yourDateValue);
让我们创建包含文档的集合。以下是查询
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Larry","UserMessage":"Hi","UserMessagePostDate":new Date("2012-09-24")});{
"acknowledged" : true,
"insertedId" : ObjectId("5c9cca58a629b87623db1b16")
}
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Chris","UserMessage":"Hello","UserMessagePostDate":new Date("2015-12-31")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9cca71a629b87623db1b17")
}
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Robert","UserMessage":"Bye","UserMessagePostDate":new Date("2019-01-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9cca85a629b87623db1b18")
}
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.insertDocumentWithDateDemo.find().pretty();
这将产生以下输出
{"_id" : ObjectId("5c9cca58a629b87623db1b16"),
"UserName" : "Larry",
"UserMessage" : "Hi",
"UserMessagePostDate" : ISODate("2012-09-24T00:00:00Z")
}
{
"_id" : ObjectId("5c9cca71a629b87623db1b17"),
"UserName" : "Chris",
"UserMessage" : "Hello",
"UserMessagePostDate" : ISODate("2015-12-31T00:00:00Z")
}
{
"_id" : ObjectId("5c9cca85a629b87623db1b18"),
"UserName" : "Robert",
"UserMessage" : "Bye",
"UserMessagePostDate" : ISODate("2019-01-01T00:00:00Z")
}
以上是 如何在MongoDB中插入带有日期的文档? 的全部内容, 来源链接: utcz.com/z/321988.html