首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

MongoDB 查詢時間範圍:同一鍵不能重複 put,正確用法是單個 BasicDBObject 包含 $gte/$lte

     編輯:程式設計綜合問答

錯誤代碼:

ref.put("clock_time", new BasicDBObject("$lte","2015/01/21 17:57:55"));
ref.put("clock_time", new BasicDBObject("$gte","2015/01/21 17:57:51"));
// 第二行覆蓋第一行,只生效一邊

正確寫法

BasicDBObject timeRange = new BasicDBObject();
timeRange.put("$gte", "2015/01/21 17:57:51");
timeRange.put("$lte", "2015/01/21 17:57:55");
ref.put("clock_time", timeRange);

進階:使用 ISODate 而非字符串

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
Instant start = LocalDateTime.parse("2015/01/21 17:57:51", fmt).atZone(ZoneId.systemDefault()).toInstant();
Instant end   = LocalDateTime.parse("2015/01/21 17:57:55", fmt).atZone(ZoneId.systemDefault()).toInstant();

BasicDBObject timeRange = new BasicDBObject();
timeRange.put("$gte", Date.from(start));
timeRange.put("$lte", Date.from(end));
ref.put("clock_time", timeRange);
  • 存儲為 BSON Date(8 字節),範圍查詢走索引極快。
  • 字符串比較受語言環境、格式影響,易出錯。

Java 驅動 3.x+ 新語法

Bson filter = Filters.and(
    Filters.gte("clock_time", startDate),
    Filters.lte("clock_time", endDate)
);
FindIterable iter = collection.find(filter);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved