javamongodbmongodb-java-3.3.0

Fetch _id of a Document in MongoDB 3.3.0 above


Trying to refactor a lot of code from one of our services I ended up using a piece of code as :

Document documentObject;
String docMongoId = ((DBObject) documentObject).removeField("_id").toString();

which though not on compiling but during execution has resulted into

java.lang.ClassCastException: com.pack.model.Document cannot be cast to com.mongodb.DBObject

wherein Document is a type defined by us. We now have a piece of code as follows :

MongoCollection<Document> dbCollection = mongoClient.getDatabase("dbName")
                .getCollection("collectionName", Document.class);

Seeking help, already went through few links -

Get ID of last inserted document in a mongoDB w/ Java driver

MongoError: cannot change _id of a document

How to query documents using "_id" field in Java mongodb driver?

which mostly suggest using BasicDBObject and we don't want to be using the older context anymore. Is there a way I can access the _id of the Document now(with client update) in java?

Please do ask for any additional or missing information required here.


Solution

  • The idea is to convert from bson type Document to your model Document. Added sample class demonstrating the use.

    import com.mongodb.MongoClient;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import com.mongodb.client.MongoDatabase;
    import org.bson.types.ObjectId;
    
    public class Mongo {
    
        public static void main(String[] args) {
    
            MongoClient mongoClient = new MongoClient();
    
            MongoDatabase db = mongoClient.getDatabase("dbName");
    
            MongoCollection <org.bson.Document> dbCollection = db.getCollection("collectionName", org.bson.Document.class);
    
            MongoCursor <org.bson.Document> iterator = dbCollection.find().iterator();
    
            while (iterator.hasNext()) {
                org.bson.Document inDoc = iterator.next();
                Document outDoc = new Document();
                outDoc.setId(inDoc.getObjectId("_id"));
                outDoc.setName(inDoc.getString("name"));
                System.out.print(outDoc.toString());
            }
    
        }
    
    
        public static class Document {
    
            private ObjectId id;
            private String name;
    
            public ObjectId getId() {
                return id;
            }
    
            public void setId(ObjectId id) {
                this.id = id;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            @Override
            public String toString() {
                return "Document{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
            }
    
        }
    }