1. 程式人生 > >mongodb中字串日期的比較

mongodb中字串日期的比較

在java專案中碰到操作mongodb中的字串型別的日期,剛開始挺坑的,沒有掌握要領.下面是我的一些總結.

1,因為mongodb中的欄位是String型別的,比如:"date" : "2017-06-28"

 所以我們在java專案中要將其對應的欄位定義為同樣的型別.

2,在專案中作比較的時候直接按照如下的方式來,簡單粗暴.

String startDate;


String endDate


Query query=new Query(Criteria.where("date").gte(startDate).lte(endDate));

這樣就可以了.

3,注意在mongodb的命令列中這樣使用.

db.getCollection('daily_user_actives').find({"date":{$gte:"2017-01-01",$lte:"2017-03-28"}})

查詢到的結果如下:

/* 1 */
{
    "_id" : ObjectId("592f9e89e51258b1ba651d3f"),
    "appid" : "01F3334T9P3W10534r3R",
    "channel" : "10035",
    "country" : "--",
    "date" : "2017-03-28",
    "actives" : NumberLong(8)
}


/* 2 */
{
    "_id" : ObjectId("592f9e89e51258b1ba651c64"),
    "appid" : "01F3334T9P3W10534r3R",
    "channel" : "10035",
    "country" : "AE",
    "date" : "2017-03-28",
    "actives" : NumberLong(2)
}

ps:上面的命令列中的 "date","2017-01-01" 中的雙引號都是不能省略的.寫命令的時候先看看原來資料的儲存型別及方式,切勿任性.

MongoDB有自己的時間型別ISODate


db.test.insert({"mark":1,"mark_time":new Date()})


db.test.insert({"mark":2,"mark_time":Date()})

db.test.find({})

{
    "_id" : ObjectId("595444b1f004583b9a95a80f"),
    "mark" : 1.0,
    "mark_time" : ISODate("2017-06-29T00:07:13.511Z")
}


{
    "_id" : ObjectId("595444caf004583b9a95a810"),
    "mark" : 2.0,
    "mark_time" : "Thu Jun 29 2017 08:07:38 GMT+0800 (CST)"
}