【问题标题】:Extract ISODate as date string from MongoDb using Java driver 3.8使用 Java 驱动程序 3.8 从 MongoDb 中提取 ISODate 作为日期字符串
【发布时间】:2018-12-19 10:03:33
【问题描述】:

下面是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);

【问题讨论】:

  • 您好,我正在使用 java 驱动程序 3.8 和 mongo db 3.2.6 发生上述问题,但 java 驱动程序 3.6 工作正常有什么想法吗?

标签: java mongodb datetime mongodb-query mongo-java-driver


【解决方案1】:

如果您将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));

【讨论】:

  • 不要在格式模式字符串中硬编码Z,你会得到不正确的结果。总的来说,请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 的表现要好得多。
  • 我不清楚OP甚至需要转换为字符串,我认为答案的关键方面是使用Document.getDate()而不是Document.toJson()。重新包含SimpleDateFormat;我不想对 OP 使用的 Java 版本做出任何假设。
  • 我发现下面代码的解决方案正在运行 System.out.println("output (JSON) = " + com.mongodb.util.JSON.serialize(myDoc));
【解决方案2】:

这与 Document 对象的 toJson 方法调用有关。 从 java 文档中,它说默认使用的 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 2017-09-04
    • 2018-09-19
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多