Mongo Java 驱动程序提供了JSON.parse(String query)
一种将查询转换为DBObject
.
public void find() {
DBObject query = JSON.parse("{name:{$exists:true}}");
DBCursor cursor = collection.find(query);
}
使用Jackson对象可以以相同的方式取消/编组:
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());
}
幸运的是,库bson4jackson允许使用 Jackson 对对象进行 un/marshalled,而无需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());
}
但是,不幸的是,这种技术似乎不适用于查询。有没有办法使用 bson4jackson 将字符串编组到 DBObject?喜欢:
public void find() {
DBObject query = bsonMarshall("{name:{$exists:true}}");
DBCursor cursor = collection.find(query);
}
非常感谢。