[英]Extract ISODate as date string from MongoDb using Java driver 3.8
以下是 mongo 集合:
{"_id":ObjectId("5a8f997fcdc2960adae4f919"),"COBDate":ISODate("2018-02-15T18:30:00.000Z"),"Version":1}
從 mongo 中提取 COBDate 的代碼
MongoCollection<Document>collection=db.getCollection(collectionName);
String jsonMessage=collection.find().iterator().next().toJson;
JSONObject message=new JSONObject(jsonMessage);
String date=message.get(COBDate).toString();
但它將COBDate
的值提取為{"$date":1518719400000}
。
有人可以幫助我以某種日期格式獲取它,例如"2018-02-15T18:30:00.000Z"
?
mongo Driver 3.8 和 mongodb 3.2.6 我遇到了上述問題。 mongo 驅動程序 3.6 工作正常...
解決方案:-
// or use a connection string
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("testdb");
MongoCollection<Document> collection = database.getCollection("user");
//JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);
//System.out.println(doc.toJson(writerSettings));
Document myDoc = collection.find().first();
//System.out.println(myDoc.toJson(writerSettings));
System.out.println("output (JSON) = " + com.mongodb.util.JSON.serialize(myDoc));
System.out.println("output (JSON) = " + myDoc);
如果您將find
響應分配給org.bson.Document
(而不是在其上調用toJson()
),那么您可以以特定於類型的方式讀取其任何屬性。 對於Date
屬性,這意味着調用document.getDate("...")
。
例如:
MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");
Document document = collection.find().iterator().next();
// now you have a Date object ...
Date cob = document.getDate("COBDate");
/// ... which you can use _as is_ or format into a String as follows ...
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
/// this will print: 2018-02-15T18:30:00.000Z
System.out.println(df.format(cob));
這與 Document 對象的 toJson 方法調用有關。 從java doc它說默認使用的JsonMode是STRICT。
/**
* Gets a JSON representation of this document using the {@link org.bson.json.JsonMode#STRICT} output mode, and otherwise the default
* settings of {@link JsonWriterSettings.Builder} and {@link DocumentCodec}.
*
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the document contains types not in the default registry
* @see #toJson(JsonWriterSettings)
* @see JsonWriterSettings
*/
@SuppressWarnings("deprecation")
public String toJson() {
return toJson(new JsonWriterSettings());
}
STRICT 模式將返回 Epoch 格式的日期值。如果您需要 ISO 格式的日期值,您應該將 JsonWriter 配置為使用 RELAXED 模式。
例如:- 將構建器作為 toJson 方法的參數傳遞。它應該為您提供 ISO 格式的日期值
使用myDoc.toJson(JsonWriterSettings.builder().build());
因為構建器默認為 RELAXED 模式
MongoCollection<Document>collection=db.getCollection(collectionName);
String jsonMessage=collection.find().iterator().next().toJson(JsonWriterSettings.builder().build());
JSONObject message=new JSONObject(jsonMessage);
String date=message.get(COBDate).toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.