List of usage examples for com.mongodb.client.result UpdateResult getModifiedCount
public abstract long getModifiedCount();
From source file:data.Activity.java
License:Open Source License
public void updateInDb(DBManagerMongo manager) throws Exception { MongoCollection<Document> coll = manager.getDb().getCollection("activity"); Document toUpdate = new Document("hash", getLocalHash()).append("project_phase_id", getProjectPhaseId()) .append("project_id", getProjectId()).append("user_login_name", getUserLoginName()) .append("description", getDescription()) .append("start_time", Date.from(getStart().toLocalDateTime().atZone(ZoneId.of("UTC")).toInstant())) .append("end_time", Date.from(getStop().toLocalDateTime().atZone(ZoneId.of("UTC")).toInstant())) .append("comment", getComments()).append("id", getId()); UpdateResult result = coll.replaceOne(and(eq("id", getId()), eq("hash", getRemoteHash())), toUpdate); if (result.getModifiedCount() != 1) throw new Exception("Record was modified or not found"); setRemoteHash(getLocalHash());/* w ww . jav a 2 s . c om*/ }
From source file:data.Project.java
License:Open Source License
public void updateInDb(DBManagerMongo manager) throws Exception { MongoCollection<Document> coll = manager.getDb().getCollection("project"); Document toUpdate = new Document("hash", getLocalHash()).append("name", getName()) .append("description", getDescription()).append("id", getId()).append("hash", getLocalHash()); UpdateResult result = coll.replaceOne(and(eq("id", getId()), eq("hash", getRemoteHash())), toUpdate); if (result.getModifiedCount() != 1) throw new Exception("Record was modyfied or not found"); setRemoteHash(getLocalHash());/*from w w w . j av a 2 s . com*/ }
From source file:data.ProjectMember.java
License:Open Source License
public void updateInDb(DBManagerMongo manager) throws Exception { MongoCollection<Document> coll = manager.getDb().getCollection("project_member"); Document toUpdate = new Document("hash", getLocalHash()).append("user_login_name", getUserLoginName()) .append("project_id", getProjectId()).append("role", getRole().name()); UpdateResult result = coll .replaceOne(and(and(eq("user_login_name", getUserLoginName()), eq("hash", getRemoteHash())), eq("project_id", getProjectId())), toUpdate); if (result.getModifiedCount() != 1) throw new Exception("Record was modyfied or not found"); setRemoteHash(getLocalHash());/* w w w .jav a 2 s . c o m*/ }
From source file:data.ProjectPhase.java
License:Open Source License
public void updateInDb(DBManagerMongo manager) throws Exception { MongoCollection<Document> coll = manager.getDb().getCollection("project_phase"); Document toUpdate = new Document("hash", getLocalHash()).append("name", getName()) .append("project_id", getProjectId()).append("id", getId()); UpdateResult result = coll.replaceOne(and(eq("id", getId()), eq("hash", getRemoteHash())), toUpdate); if (result.getModifiedCount() != 1) throw new Exception("Record was modyfied or not found"); setRemoteHash(getLocalHash());/*from www . j a va 2s .co m*/ }
From source file:data.User.java
License:Open Source License
public void updateInDb(DBManagerMongo manager) throws Exception { MongoCollection<Document> coll = manager.getDb().getCollection("user"); Document toUpdate = new Document("hash", getLocalHash()).append("login_name", getLoginName()) .append("first_name", getFirstName()).append("last_name", getLastName()).append("email", getEmail()) .append("salt", getSalt()).append("password", getPassword()).append("role", getRole().name()); UpdateResult result = coll.replaceOne(and(eq("login_name", getLoginName()), eq("hash", getRemoteHash())), toUpdate);//from w w w .j a va 2 s . c o m if (result.getModifiedCount() != 1) throw new Exception("Record was modyfied or not found"); setRemoteHash(getLocalHash()); }
From source file:examples.tour.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 ww w . j a v a 2s. c om*/ public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); // 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>() { 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()); // Aggregation collection .aggregate( asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))) .forEach(printBlock); myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), set("i", 110)); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("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:io.lumeer.storage.mongodb.dao.system.MongoUserDao.java
License:Open Source License
@Override public void deleteUserGroups(final String organizationId, final String userId) { Bson pullUser = Updates.pull(UserCodec.ALL_GROUPS, Filters.eq(UserCodec.ORGANIZATION_ID, organizationId)); try {/* w w w . j a v a2 s . co m*/ UpdateResult result = databaseCollection().updateOne(idFilter(userId), pullUser); if (result.getModifiedCount() != 1) { throw new StorageException("User '" + userId + "' has not been deleted."); } } catch (MongoException ex) { throw new StorageException("Cannot remove organization " + organizationId + "from user " + userId, ex); } }
From source file:joliex.mongodb.MongoDbConnector.java
@RequestResponse public Value updateMany(Value request) throws FaultException { try {/* ww w . ja va2 s . c o m*/ String collectionName = request.getFirstChild("collection").strValue(); Value v = Value.create(); BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue()); prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter")); printlnJson("Update filter", bsonQueryDocument); BsonDocument bsonDocument = BsonDocument.parse(request.getFirstChild("documentUpdate").strValue()); printlnJson("Update documentUpdate", bsonDocument); prepareBsonQueryData(bsonDocument, request.getFirstChild("documentUpdate")); printlnJson("Update documentUpdate", bsonDocument); if (request.hasChildren("writeConcern")) { WriteConcern writeConcern = new WriteConcern(); if (request.getFirstChild("writeConcern").hasChildren("journal")) { writeConcern.withJournal( request.getFirstChild("writeConcern").getFirstChild("journal").boolValue()); } if (request.getFirstChild("writeConcern").hasChildren("w")) { if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) { writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue()); } if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) { writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue()); } } if (request.getFirstChild("writeConcern").hasChildren("timeout")) { writeConcern.withWTimeout( request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(), TimeUnit.MILLISECONDS); } db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern); } if (request.hasChildren("options")) { UpdateOptions updateOptions = new UpdateOptions(); updateOptions.upsert(request.getFirstChild("options").getFirstChild("upsert").boolValue()); updateOptions.bypassDocumentValidation( request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue()); UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class) .updateMany(bsonQueryDocument, bsonDocument, updateOptions); v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount())); v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount())); } else { UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class) .updateMany(bsonQueryDocument, bsonDocument); v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount())); v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount())); } return v; } catch (MongoException ex) { throw new FaultException("MongoException", ex); } catch (JsonParseException ex) { throw new FaultException("JsonParseException", ex); } }
From source file:joliex.mongodb.MongoDbConnector.java
@RequestResponse public Value update(Value request) throws FaultException { try {/*from w w w .j a v a 2 s. com*/ Value v = Value.create(); String collectionName = request.getFirstChild("collection").strValue(); BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue()); prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter")); printlnJson("Update filter", bsonQueryDocument); BsonDocument bsonDocument = BsonDocument.parse(request.getFirstChild("documentUpdate").strValue()); printlnJson("Update documentUpdate", bsonDocument); prepareBsonQueryData(bsonDocument, request.getFirstChild("documentUpdate")); printlnJson("Update documentUpdate", bsonDocument); showLog(); if (request.hasChildren("writeConcern")) { WriteConcern writeConcern = new WriteConcern(); if (request.getFirstChild("writeConcern").hasChildren("journal")) { writeConcern.withJournal( request.getFirstChild("writeConcern").getFirstChild("journal").boolValue()); } if (request.getFirstChild("writeConcern").hasChildren("w")) { if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) { writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue()); } if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) { writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue()); } } if (request.getFirstChild("writeConcern").hasChildren("timeout")) { writeConcern.withWTimeout( request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(), TimeUnit.MILLISECONDS); } db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern); } if (request.hasChildren("options")) { UpdateOptions updateOptions = new UpdateOptions(); updateOptions.upsert(request.getFirstChild("options").getFirstChild("upsert").boolValue()); updateOptions.bypassDocumentValidation( request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue()); UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class) .updateOne(bsonQueryDocument, bsonDocument, updateOptions); v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount())); v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount())); } else { UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class) .updateOne(bsonQueryDocument, bsonDocument); v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount())); v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount())); } return v; } catch (MongoException ex) { throw new FaultException("MongoException", ex); } }
From source file:mongodb.clients.percunia.mongo.AsyncClient.java
License:Apache License
@Override public void removeDocumentField(final String collectionName, Criteria criteria, String field, final ResultCallback callback) { MongoCollection<Document> collection = database.getCollection(collectionName); collection.updateOne(criteria.getRestrictions(), unset(field), new SingleResultCallback<UpdateResult>() { @Override// w w w . j av a2s .c o m public void onResult(final UpdateResult result, final Throwable t) { onUpdateResultAction(result, t, result.getModifiedCount() + " " + collectionName + " entity successfully updated", callback); } }); }