mongodb中根據時間范圍進行查詢


時間字段處於數據頂層結構中

例如: 當前數據庫中有1000條數據,數據的結構為:

{
    "_id" : { "$oid" : "587dc4069f527a223ca81f4f" }, 
    "index" : 664, 
    "create" : { "$date" : 1484637190565 } }

時間字段create就處於數據的最頂層,這種類型的數據查詢實現其實很簡單,是需要使用eq、gt等方法即可,例如:
- 實現方法一

collection.find(
        new Document("create", 
            new Document("$gt", new Date(1484637189630l))
        )
    ).forEach(new Block<Document>() {
                public void apply(Document document) {
                    System.out.println(document.toJson());
                }
    });
  • 實現方法二
collection.find(gt("create",new Date(1484637189630l))).forEach(
    new Block<Document>() {
                public void apply(Document document) {
                    System.out.println(document.toJson());
                }
});

時間字段處於數據的嵌套數據結構中

例如:當前數據庫中有1000條數據,數據的結構為:

{ 
    "_id" : { "$oid" : "587dc4069f527a223ca81f51" }, 
    "index" : 666, 
    "times" : { "ct" : { "$date" : 1484637190587 } } }

時間字段ct處於嵌套數據times中,遇到這種結構的數據,還需要根據時間為條件進行查詢數據,就需要以ct的完整查詢路徑為查詢條件進行查詢,例如:
- 實現方法一

collection.find(
        new Document("times.ct", 
            new Document("$gt", new Date(1484637189630l))
        )
    ).forEach(new Block<Document>() {
                public void apply(Document document) {
                    System.out.println(document.toJson());
                }
    });
  • 實現方法二
collection.find(gt("times.ct",new Date(1484637189630l))).forEach(
    new Block<Document>() {
                public void apply(Document document) {
                    System.out.println(document.toJson());
                }
});

這兩種方法中均采用點號“.”分割,將ct的完整路徑作為查詢參數進行查詢。

這種查詢方法其實在非時間類型上也是適用,不過這是我平時沒有注意到的一個細節問題,記錄下來方便查詢。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM