简体   繁体   中英

MongoDB Java Driver Jackson Mapper MongoJack

I am looking to find the most industry standard way to achieve the following. I am writing a Java application which will manage documents in a MongoDB. Everything I have read so far points to using Mongo Java driver (3.0) for connecting to the Database then using Jackson Object Mapper to map the JSON to a Class for easy manipulation. Then using json.org:

JSONObject json = new JSONObject(mapper.writeValueAsString(user));

To get it back into Mongo.

 Document doc1 = Document.parse(json.toString());
 collection.insertOne(doc1)

So with the new 3.0 driver things have changed a little as DBObject is no longer recommended.

So what is the best way to get documents from Mongo edit and update them and then save the updated document.

MongoCollection<Document> collection = database.getCollection("mycoll");

Does:

MongoCollection<BasicDBObject> collection = database.getCollection("mycoll", BasicDBObject.class);

MongoCollection<MyObject> collection = database.getCollection("mycoll", MyObject.class);

Does the MyObject ability remove the need to using object mapping ?

As you can see I'm a little confused now and any help to straighten out the best was to do this for Driver 3.0 > would be great.

The latest MongoJack currently available (2.5.1 from November 2015) still uses the now deprecated DBCollection (now, as of the MongoDb driver 3.0).

So you could still do this if you wanted:

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("databaseName");
DBCollection coll = db.getCollection("my.collection");
JacksonDBCollection<MyDomainObject, String> wrapped =
  JacksonDBCollection.wrap(coll, MyDomainObject.class, String.class);

In your question, you bring up the Codec registry capability of the MongoDb driver 3.0 and essentially ask, is MongoJack still relevant since the native driver has this capability built-in?

I have not written a codec yet, but it seems to require some fair amount of boiler plate code - a far cry from the simplicity of MongoJack. Take a look at an example in this blog post .

In my opinion, a new version of MongoJack would take advantage of the Codec capabilities of the driver and abstract them to something as simple as what the current version of MongoJack provides. I have posted a question about this on the MongoJack github project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM