使用String在Java中创建Mongo查询

时间:2012-10-08 20:26:07

标签: java mongodb jackson mongomapper bson

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允许对象在不需要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将String编组到DBObject?像:

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

非常感谢。

0 个答案:

没有答案