mongo-java-driver -3.2.2学习笔记-06-CRUD

mongo-java-driver -3.2.2学习笔记-06-CRUD
example1

MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycoll");

// insert a document
Document document = new Document("x", 1)
collection.insertOne(document);
document.append("x", 2).append("y", 3);

// replace a document
collection.replaceOne(Filters.eq("_id", document.get("_id")), document);

// find documents
List<Document> foundDocument = collection.find().into(new ArrayList<Document>());

example 2:

// Pass BasicDBObject.class as the second argument
MongoCollection<BasicDBObject> collection = database.getCollection("mycoll", BasicDBObject.class);

// insert a document
BasicDBObject document = new BasicDBObject("x", 1)
collection.insertOne(document);
document.append("x", 2).append("y", 3);

// replace a document
collection.replaceOne(Filters.eq("_id", document.get("_id"), document);

// find documents
List<BasicDBObject> foundDocument = collection.find().into(new ArrayList<BasicDBObject>());

important!!!!!
mongo 进行不同的读写配置,见官方文档

// CORRECT: The results of the method calls are chained and the final one is referenced 
// by collection 
MongoCollection<Document> collection = database.getCollection("mycoll")
                                                .withWriteConcern(WriteConcern.JOURNALED)
                                                .withReadPreference(ReadPreference.primary())
                                                .withCodecRegistry(newRegistry);

// INCORRECT: withReadPreference returns a new instance of MongoCollection
// It does not modify the collection it's called on.  So this will
// have no effect
collection.withReadPreference(ReadPreference.secondary());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值