以前はを使用mongo-java-driver 3.0.4
していましたが、コードの特定のブロックにこの実装があります-
DBCollection docCollection = mongoClient.getDB(dbName).getCollection(collectionName);
Map<String, Object> docMap = doc.toMap(); // where doc is the CustomDocument
DBObject currentObj = docCollection.findOne(new QueryBuilder().put("id").is(doc.getId()).get());
if(currentObj == null) {
docCollection.insert(new BasicDBObject(docMap));
} else {
docCollection.update(currentObj, new BasicDBObject(docMap));
}
私が今達成しようとしているのはmongo-java-driver 3.3.0
、非推奨のクラスとメソッドを取り除くためにコードを使用して更新することです。上記のコードに対応して私が試したのは-
MongoCollection<CustomDocument> docCollections = mongoClient.getDatabase(dbName).getCollection(collectionName, CustomDocument.class);
Bson filter = Filters.eq("id", doc.getId()); // where doc is the CustomDocument
FindIterable<Document> documentList = docCollections.find(filter);
if (documentList == null) {
docCollections.insertOne(doc);
} else {
docCollections.findOneAndUpdate(filter, new BasicDBObject(docMap));
}
私がまだ不足しているのはfindOne
、コード内のコレクションからの実装insert
と、update
それに応じて実行されるチェックベースのアクションです。
これに対する解決策/提案は大歓迎です。
の実装で遊んでいる解決策を見つけましたmongo-java-driver 3.3.0
。
実行する簡単な方法はfindOne
次のとおりです-
MongoCollection<CustomDocument> docCollections = mongoClient.getDatabase(dbName).getCollection(collectionName, CustomDocument.class);
CustomDocument firstDocument = docCollections.find(filter).first(); //first for findOne
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加