![](/img/trans.png)
[英]How do I query document like this in Java Driver for MongoDb?
[英]How do i do a Save operation on a MongoDB collection using the Java driver?
我只是从Python切换过来,需要继续使用MongoDB数据库。 一个特定的任务是将传入文档(在本例中为tweet)保存到集合中以进行归档。 一条推文可能会多次出现,所以我更喜欢使用save()
不是insert()
因为如果文档已经存在于集合中,则前者不会引发错误。 但是,似乎MongoDB的Java驱动程序不支持保存操作。 我想念什么吗?
编辑:供参考,我正在使用此库'org.mongodb:mongodb-driver:3.0.2'
示例代码:
MongoCollection<Document> tweets = db.getCollection("tweets");
...
Document tweet = (Document) currentDocument.get("tweet");
tweets.insertOne(tweet);
当推文已经存在时,最后一行引发此错误:
Exception in thread "main" com.mongodb.MongoWriteException: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.tweets.$_id_ dup key: { : ObjectId('55a403b87f030345e84747eb') }
使用3.x MongoDB Java驱动程序,您可以像下面这样使用MongoCollection#replaceOne(Document, Document, UpdateOptions)
:
MongoClient mongoClient = ...
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> tweets = db.getCollection("tweets");
...
Document tweet = (Document) currentDocument.get("tweet");
tweets.replaceOne(tweet, tweet, new UpdateOptions().upsert(true));
这样可以避免重复键错误。 但是,这与使用DBCollection#save(DBObject)
并不完全相同,因为它使用整个Document
作为过滤器,而不仅仅是_id字段。 要镜像旧的save方法,您必须编写如下代码:
public static void save(MongoCollection<Document> collection, Document document) {
Object id = document.get("_id");
if (id == null) {
collection.insertOne(document);
} else {
collection.replaceOne(eq("_id", id), document, new UpdateOptions().upsert(true));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.