2

Mongo Java driver provides a JSON.parse(String query) method to convert query into DBObject.

public void find() {
    DBObject query = JSON.parse("{name:{$exists:true}}");
    DBCursor cursor = collection.find(query);
}

Using Jackson objects can be un/marshalled the same way:

DBCollection collection = new Mongo().getDB("db").getCollection("friends");

public void save() {
    DBObject document = jsonMarshall(new Friend("John", 24));
    collection.save(document);
    // db.peoples.save({name: 'John', age: 24})
}

ObjectMapper jsonMapper = new ObjectMapper();

public DBObject jsonMarshall(Object obj) throws Exception {
    Writer writer = new StringWriter();
    jsonMapper.writer().writeValue(writer, obj);
    return (DBObject) JSON.parse(writer.toString());
}

Fortunately, the library bson4jackson allows objects to be un/marshalled with Jackson without the need of JSON.parse(String):

public void save() {
    DBObject document = bsonMarshall(new Friend("John", 24));
    collection.save(document);
    // db.peoples.save({name: 'John', age: 24})
}

ObjectMapper bsonMapper = new ObjectMapper(new BsonFactory());

public DBObject bsonMarshall(Object obj) throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bsonMapper.writer().writeValue(output, obj);
    return new LazyWriteableDBObject(output.toByteArray(), new LazyBSONCallback());
}

But, unfortunately, this technique do not seems to work with queries. Is there a way to use bson4jackson to marshall a String to a DBObject? Like:

public void find() {
    DBObject query = bsonMarshall("{name:{$exists:true}}");
    DBCursor cursor = collection.find(query);
}

Thanks a lot.

yves amsellem
  • 7,106
  • 5
  • 44
  • 68
  • 2
    Does this library help you ? http://jongo.org/ – Louisa Oct 09 '12 at 15:34
  • 1
    @Louisa Your answer is funny: I'm the co-writer of this Java library ;-) And, for the moment on, Jongo uses `JSON.parse()` for query marshalling. Thanks anyway. – yves amsellem Oct 09 '12 at 15:50
  • @yvesamsellem slight side note; is Jongo still being updated? Seems to be no official release alongside Mongo 3.x? – whitfin Nov 17 '15 at 06:36
  • @zackehh Jongo is still updated but at a slower pace now, because the feature list match our needs. If you got a specific feature in mind, go ahead and create a github issue (or better, a pull request). – yves amsellem Nov 17 '15 at 11:26

0 Answers0