findOne 实现在升级到 mongo-java-driver 3.3.0 时发生了变化
findOne implementation changed while upgrading to mongo-java-driver 3.3.0
我们之前使用的是 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
执行的基于检查的操作。
欢迎任何solution/suggestion。
findOne()
在 nodeJS 中也已弃用。
find().limit(1)
是备选方案。
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne
我在 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
我们之前使用的是 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
执行的基于检查的操作。
欢迎任何solution/suggestion。
findOne()
在 nodeJS 中也已弃用。
find().limit(1)
是备选方案。
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne
我在 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