2016-09-14 47 views
0

我們需要存儲事務數據的多個集合(僅插入和不更新)。憑藉我對NoSQL DB的有限瞭解,我覺得Mongo DB是DB的簡單和不錯的選擇。我的方法是否正確?用於事務DB和日期操作的Mongo DB

同時查詢我將不得不篩選日期之間的記錄。我找不到在Mongo集合中存儲和過濾「日期」類型的適當示例。有人可以幫助我適當的方式來存儲「日期」類型和寫過濾器查詢嗎?

回答

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