How do i do a Save operation on a MongoDB collection using the Java driver? -


i switch on python, , need continue work mongodb database. 1 particular task save incoming document (in case, tweet) collection archiving. tweet comes in multiple times, prefer use save() on insert() since former not raise error if document exists in collection. seems java driver mongodb not support save operation. missing something?

edit: reference, i'm using library 'org.mongodb:mongodb-driver:3.0.2'

example code:

mongocollection<document> tweets = db.getcollection("tweets"); ... document tweet = (document) currentdocument.get("tweet"); tweets.insertone(tweet); 

the last line raise error when tweet exists:

exception in thread "main" com.mongodb.mongowriteexception: insertdocument :: caused :: 11000 e11000 duplicate key error index: db.tweets.$_id_ dup key: { : objectid('55a403b87f030345e84747eb') }

using 3.x mongodb java driver can use mongocollection#replaceone(document, document, updateoptions) this:

mongoclient mongoclient = ... mongodatabase database = mongoclient.getdatabase("mydb"); mongocollection<document> tweets = db.getcollection("tweets"); ... document tweet = (document) currentdocument.get("tweet"); tweets.replaceone(tweet, tweet, new updateoptions().upsert(true)); 

this avoid duplicate key error. however, not same using dbcollection#save(dbobject), since uses whole document filter instead of _id field. mirror old save method, have write this:

public static void save(mongocollection<document> collection, document document) {     object id = document.get("_id");     if (id == null) {         collection.insertone(document);     } else {         collection.replaceone(eq("_id", id), document, new updateoptions().upsert(true));     } } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -