List of usage examples for com.mongodb.client.result UpdateResult getModifiedCount
public abstract long getModifiedCount();
From source file:mongodb.clients.percunia.mongo.AsyncClient.java
License:Apache License
void Recurse(final int index, final String entityName, final Criteria criteria, final String field, final String subField, final List<String> subFieldValues, final ResultCallback callback) { if (index == -1) { callback.onSuccess(""); return;/*from www . j a va2s . c om*/ } MongoCollection<Document> collection = database.getCollection(entityName); collection.updateOne(criteria.getRestrictions(), pull(field, new Document(subField, subFieldValues.get(index))), new SingleResultCallback<UpdateResult>() { @Override public void onResult(final UpdateResult result, final Throwable t) { if (t == null) { if (result.getModifiedCount() > 0) { Recurse(index - 1, entityName, criteria, field, subField, subFieldValues, callback); } else { callback.onError(errorMessage); } } else { callback.onError(t.toString()); t.printStackTrace(); } } }); }
From source file:mongodb.clients.percunia.mongo.AsyncClient.java
License:Apache License
private void onUpdateResultAction(UpdateResult result, Throwable t, String message, ResultCallback callback) { if (t == null) { if (result.getModifiedCount() > 0) { logger.info(message);// w ww . java 2 s . com callback.onSuccess(""); } else { callback.onError(errorMessage); } } else { callback.onError(t.toString()); } }
From source file:mongodb.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string *//*from w ww. j a va2 s. c om*/ public static void main(final String[] args) { //represents a pool of connections to the database MongoClient mongoClient = new MongoClient("10.9.17.105", 27017); // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("test"); // get a handle to the "test" collection MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); collection.find().forEach(printBlock); // Clean up // database.drop(); // release resources mongoClient.close(); }
From source file:mongofx.ui.result.tree.ResultTreeController.java
License:Open Source License
private void updateObject(Document doc, Object id) { try {/*from w w w. j a v a2s .com*/ UpdateResult updateResult = mongoDatabase.getMongoDb().getCollection(collectionName) .replaceOne(new BasicDBObject("_id", id), doc); if (updateResult.getModifiedCount() < 1) { Alert alert = new Alert(AlertType.ERROR); alert.setHeaderText("Document update filed"); alert.show(); } else { popupService.showInfo("Document updated"); } } catch (Exception ex) { log.warn("Error update document", ex); Alert alert = new Alert(AlertType.ERROR); alert.setHeaderText("Document update filed"); alert.setContentText(ex.getMessage()); alert.show(); } }
From source file:mongoSample.MongoSample.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args//from w ww. ja v a2s . c om * takes an optional single argument for the connection string */ public static void main(final String[] args) { String mongoServer = args[0]; MongoClient mongoClient = new MongoClient(mongoServer); MongoDatabase database = mongoClient.getDatabase("sakila"); MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest // earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can // explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); // collection.find().forEach(printBlock); // Clean up //database.drop(); // release resources mongoClient.close(); }
From source file:org.apache.drill.exec.store.mongo.config.MongoPersistentStore.java
License:Apache License
@Override public boolean putIfAbsent(String key, V value) { try {//from www . ja va 2 s .c o m Bson query = Filters.eq(DrillMongoConstants.ID, key); Bson update = Updates.set(pKey, bytes(value)); UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true)); return updateResult.getModifiedCount() == 1; } catch (Exception e) { logger.error(e.getMessage(), e); throw new DrillRuntimeException(e.getMessage(), e); } }
From source file:org.apache.eagle.alert.metadata.impl.MongoMetadataDaoImpl.java
License:Apache License
private <T> OpResult addOrReplace(MongoCollection<Document> collection, T t) { BsonDocument filter = new BsonDocument(); if (t instanceof StreamDefinition) { filter.append("streamId", new BsonString(MetadataUtils.getKey(t))); } else if (t instanceof PublishmentType) { filter.append("type", new BsonString(MetadataUtils.getKey(t))); } else if (t instanceof AlertPublishEvent) { filter.append("alertId", new BsonString(MetadataUtils.getKey(t))); } else {//from w w w. j a va 2 s . c om filter.append("name", new BsonString(MetadataUtils.getKey(t))); } String json = ""; OpResult result = new OpResult(); try { json = mapper.writeValueAsString(t); UpdateOptions options = new UpdateOptions(); options.upsert(true); UpdateResult ur = collection.replaceOne(filter, Document.parse(json), options); // FIXME: could based on matched count do better matching... if (ur.getModifiedCount() > 0 || ur.getUpsertedId() != null) { result.code = 200; result.message = String.format("update %d configuration item.", ur.getModifiedCount()); } else { result.code = 500; result.message = "no configuration item create/updated."; } } catch (Exception e) { result.code = 500; result.message = e.getMessage(); LOG.error("", e); } return result; }
From source file:org.axonframework.mongo.eventsourcing.tokenstore.MongoTokenStore.java
License:Apache License
private void updateOrInsertTokenEntry(TrackingToken token, String processorName, int segment) { AbstractTokenEntry<?> tokenEntry = new GenericTokenEntry<>(token, serializer, contentType, processorName, segment);//from ww w . ja v a 2s. c o m tokenEntry.claim(nodeId, claimTimeout); Bson update = combine(set("owner", nodeId), set("timestamp", tokenEntry.timestamp().toEpochMilli()), set("token", tokenEntry.getSerializedToken().getData()), set("tokenType", tokenEntry.getSerializedToken().getType().getName())); UpdateResult updateResult = mongoTemplate.trackingTokensCollection() .updateOne(claimableTokenEntryFilter(processorName, segment), update); if (updateResult.getModifiedCount() == 0) { try { mongoTemplate.trackingTokensCollection().insertOne(tokenEntryToDocument(tokenEntry)); } catch (MongoWriteException exception) { if (ErrorCategory.fromErrorCode(exception.getError().getCode()) == ErrorCategory.DUPLICATE_KEY) { throw new UnableToClaimTokenException( format("Unable to claim token '%s[%s]'", processorName, segment)); } } } }
From source file:org.flywaydb.core.internal.metadatatable.MongoMetaDataTable.java
License:Apache License
@Override public boolean upgradeIfNecessary() { Document filter = Document.parse("{ version_rank: {$exists: true} }"); Document renameQuery = Document .parse("{$rename: {version_rank: '" + MetaDataDocument.INSTALLED_RANK + "'}}"); UpdateResult result = metadataCollection.updateMany(filter, renameQuery); return (result.getModifiedCount() > 0); }
From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java
License:Apache License
@Override public void updateUserAccount(UserEntity user) throws MetaStoreException, NotStoredException { if (!ObjectId.isValid(user.getId())) { throw new MetaStoreException("Invalid account ID '" + user.getId() + "'"); }//w ww . jav a 2 s . c om try { Date lastModifyTime = new Date(); UpdateResult result = userAccountCollection.updateOne(eq("_id", new ObjectId(user.getId())), new Document("$set", new Document("name", user.getName()).append("password", user.getPassword()) .append("lastModifyTime", lastModifyTime))); if (result.getModifiedCount() > 0) { user.setLastModifyTime(lastModifyTime); LOG.info("Successful to update user account '{}'", user.getName()); } else { throw new NotStoredException("Can't find user account '" + user.getId() + "'"); } } catch (MongoException e) { LOG.error("Failed to update user account", e); throw new MetaStoreException("Failed to update user account", e); } }