Mongo Async Java driver doesnt return the id in insertOne method

810 views
Skip to first unread message

sandeepsahoo2k2

unread,
Jul 25, 2016, 1:15:35 AM7/25/16
to mongodb-user

I am struggling to fix this problem where I have to get the inserted _id field for the mongodb async insertOne function. Can some one help or I have to get rid of the Async driver completely as there is no way ? following this tutoraial http://mongodb.github.io/mongo-java-driver/3.0/driver-async/getting-started/quick-tour/ ..

Note : The document is successfully inserted to mongodb with the below call but there is no way that I can get the _id from this api.

m_messages_collection.insertOne(userMessage, new SingleResultCallback<Void>() {
        @Override
        public void onResult(final Void result, final Throwable t) {
            logger.log(Level.INFO, "A new message from inserted to DB");
            //Here result is also null even though the data is inserted
            // so there is no way that I can fetch the inserted _id
} });

Jeff Yemin

unread,
Jul 25, 2016, 1:36:39 PM7/25/16
to mongodb-user
The driver writes the _id into the document before it inserts it.  So something like this will work:

final Document userMessage = new Document();
// add fields to userMessage
collection.insertOne(userMessage, new SingleResultCallback<Void>() {
@Override
public void onResult(final Void result, final Throwable t) {
       // The _id value will be available in userMessage itself 
       System.out.println(userMessage.get("_id"));
}
});


Let me know if that works for you.


Regards,
Jeff
Reply all
Reply to author
Forward
0 new messages