获取集合的时候,可以传入bean的class文件。来实现数据的绑定。
在这之前。需要自定义一个Codec类。进行数据的转换。
MongoClient client=new MongoClient(new ServerAddress("127.0.0.1",27017)); MongoDatabase db= client.getDatabase("chaoba"); CodecRegistry codecRegistry=CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(new Chaoba1Codec())); MongoCollection<Chaoba1> chaoba1 =db.getCollection("chaoba1",Chaoba1.class).withCodecRegistry(codecRegistry); // MongoCursor<Chaoba1> result=chaoba.find().iterator(); // while(result.hasNext()) { // System.out.println(result.next()); // } Chaoba1 chaoba =new Chaoba1(); chaoba.setName("Demo2"); chaoba1.insertOne(chaoba);
Codec类
package demo2; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; public class Chaoba1Codec implements Codec<Chaoba1>{ @Override public void encode(BsonWriter writer, Chaoba1 value, EncoderContext encoderContext) { // TODO Auto-generated method stub writer.writeStartDocument(); writer.writeString("name", value.getName()); // writer.writeString("sex", value.getSex()); writer.writeEndDocument(); } @Override public Class<Chaoba1> getEncoderClass() { // TODO Auto-generated method stub return Chaoba1.class; } @Override public Chaoba1 decode(BsonReader reader, DecoderContext decoderContext) { // TODO Auto-generated method stub reader.readStartDocument(); Chaoba1 chaoba1=new Chaoba1(); chaoba1.set_id(reader.readObjectId("_id")); chaoba1.setName(reader.readString("name")); // chaoba1.setSex(reader.readString("sex")); reader.readEndDocument(); return chaoba1; } }