我是一个使用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显然不是这里的专家。 –