Create a Mongo query in Java using a String

╄→гoц情女王★ 提交于 2019-12-10 23:53:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!