From c69343c8537443d278ff8fa14da586efb93ff3d8 Mon Sep 17 00:00:00 2001 From: sebx59 Date: Sat, 29 Jan 2022 06:58:08 +0100 Subject: [PATCH] Example class for BAEL-4888 (#11728) code used to illustrate the article about retrieving the MongoDB ID --- .../mongo/objectid/RetrieveIdExample.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java new file mode 100644 index 0000000000..74279bbfcd --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java @@ -0,0 +1,57 @@ +package com.baeldung.mongo.objectid; + +import java.util.Date; + +import org.bson.Document; +import org.bson.types.ObjectId; + +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; + +public class RetrieveIdExample { + + public static void main(String[] args) { + + try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) { + + MongoDatabase database = mongoClient.getDatabase("myMongoDb"); + MongoCollection collection = database.getCollection("example"); + +// Create document with user-generated ID + ObjectId generatedId = new ObjectId(); + + System.out.println(generatedId.toString()); + + Document document = new Document(); + document.put("_id", generatedId); + document.put("name", "Shubham"); + document.put("company", "Baeldung"); + collection.insertOne(document); + +// Check that the ID of the document is still the one we set + System.out.println(document.getObjectId("_id").equals(generatedId)); + + +// Create a second document by injecting the ID in the constructor + + ObjectId generatedId2 = ObjectId.get(); + + Document document2 = new Document("_id", generatedId2); + document2.put("name", "Shubham"); + document2.put("company", "Baeldung"); + collection.insertOne(document2); + + Date creationDate = generatedId.getDate(); + System.out.println(creationDate); + + int timestamp = generatedId.getTimestamp(); + + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + +}