我是一個使用MongoDB的新手。我只是通過Maven的進口最新的MongoDB的Java客戶端:MongoDB java客戶端的WriteConcern不起作用
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
然後我寫了一個非常簡單的程序測試插入操作。
//I use a replicaset
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress("10.12.16.136", 29017),
new ServerAddress("10.12.16.136", 29018),
new ServerAddress("10.12.16.136", 29019)));
//I just want to write and ignore any database errors. (This does not work)
mongoClient.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
//Get database and collection
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("realtime");
//This does not work too.
collection.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
//Make a simple object to insert. I already have a document with the same _id in the database and I don't want to see the exception via the WriteConcern operation.
Document doc = Document("longitude", longitude)
.append("latitude", latitude)
.append("velocity", velocity)
.append("soc", soc)
.append("_id", 12345678);
//WriteConcern.UNACKNOWLEDGED doesn't work. An exception will be raised.
collection.insertOne(doc);
我該如何做正確的事情?
你沒有正確閱讀所有的代碼。在所有'mongoClient.setWriteConcern(WriteConcern.UNACKNOWLEDGED)'之前也有這條線路。所以他們期待着「全球效應」。關於收集的設置只是一個後果問題。 –
@BlakesSeven編輯的回覆 –
把'.withWriteConcern(WriteConcern.UNACKNOWLEDGED)'添加到'.getDatabase()'或'.getCollection()'的末尾可能會更簡單直接。應該使用。一般來說'UNACKNOWLEDGED'非常「強力」,只有當你真的知道你在做什麼時才應該使用它。當然不是「只是」跳過重複的錯誤,因爲有更好的,「更安全」的方法,以及更少的侵入性方法。請記住OP顯然不是這裏的專家。 –