问题
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.
来源:https://stackoverflow.com/questions/12788957/create-a-mongo-query-in-java-using-a-string