您的位置:首页 > 编程语言 > Java开发

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

2017-12-05 12:41 246 查看
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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: