【问题标题】:Mongo DB for Transaction DB and Date operations用于事务数据库和日期操作的 Mongodb
【发布时间】:2017-06-25 19:57:45
【问题描述】:

我们需要存储多个事务数据集合(只有插入,没有更新)。由于我对 NoSQL DB 的了解有限,我觉得 Mongo DB 是 DB 的简单而好的选择。我的方法正确吗?

此外,在查询时,我必须过滤日期之间的记录。我找不到在 Mongo 集合中存储和过滤“日期”类型的正确示例。有人可以帮助我存储“日期”类型和编写过滤器查询的正确方法吗?

【问题讨论】:

    标签: mongodb mongodb-query nosql


    【解决方案1】:

    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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 2021-11-16
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多