我们需要存储多个事务数据集合(仅插入而不进行更新)。由于我对NoSQL DB的了解有限,我觉得Mongo DB是DB的简单而不错的选择。我的方法是否正确?
同样在查询时我将不得不在日期之间过滤记录。我找不到在Mongo集合中存储和过滤“日期”类型的正确示例。有人可以帮我正确地存储“日期”类型和编写过滤查询吗?
答案 0 :(得分:0)
MongoDB可以轻松处理存储事务数据的要求。您日期的首选格式是将其以BSON Date格式存储在您的集合中,这样更易于查询和排序。使用"新日期"下面使用ISODate()包装器正确格式化日期。
示例:
use foo_test
db.foo.drop()
db.foo.insert(
{Quote:"Many of life's failures are people who did not realize how close they were to success when they gave up.",
Author: "Thomas Edison",
Date: new Date("1931-01-31")});
db.foo.insert(
{Quote:"In this world nothing can be said to be certain, except death and taxes.",
Author: "Benjamin Frankin",
Date: new Date("1789-11-13")});
db.foo.insert(
{Quote:"Houston, we've had a problem here",
Author: "Jim Lovell - Apollo 13 Commander",
Date: new Date("1970-04-15")});
db.foo.insert(
{Quote:"There aren't many downsides to being rich, other than paying taxes and having relatives asking for money.",
Author: "Bill Murray",
Date: new Date("2005-03-14")});
查找具有特定日期的文档的示例查询,该日期仅返回样本数据的1个文档:
db.foo.find({Date: ISODate("1931-01-31")}).pretty();
{
"_id" : ObjectId("57e0a749e4901a8bc1ab69f6"),
"Quote" : "Many of life's failures are people who did not realize how close they were to success when they gave up.",
"Author" : "Thomas Edison",
"Date" : ISODate("1931-01-31T00:00:00Z")
}
查询示例查找两个日期之间的所有文档,这些文档将返回样本数据的2个文档:
db.foo.find({Date:{$gte:ISODate("1931-01-31"),$lte:ISODate("1970-05-01")}}).pretty();
{
"_id" : ObjectId("57e0a749e4901a8bc1ab69f6"),
"Quote" : "Many of life's failures are people who did not realize how close they were to success when they gave up.",
"Author" : "Thomas Edison",
"Date" : ISODate("1931-01-31T00:00:00Z")
}
{
"_id" : ObjectId("57e0a749e4901a8bc1ab69f8"),
"Quote" : "Houston, we've had a problem here",
"Author" : "Jim Lovell - Apollo 13 Commander",
"Date" : ISODate("1970-04-15T00:00:00Z")
}