2

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/marshall することができます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);
}

どうもありがとう。

4

0 に答える 0