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());