List of usage examples for com.mongodb.client.result UpdateResult getModifiedCount
public abstract long getModifiedCount();
From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java
License:Apache License
@Override public void changeUserAccountPassword(UserEntity user) throws MetaStoreException, NotStoredException { if (!ObjectId.isValid(user.getId())) { throw new MetaStoreException("Invalid account ID '" + user.getId() + "'"); }//www .j a v a 2s . c om try { Date lastModifyTime = new Date(); UpdateResult result = userAccountCollection.updateOne(eq("_id", new ObjectId(user.getId())), new Document("$set", new Document("password", user.getPassword()).append("lastModifyTime", lastModifyTime))); if (result.getModifiedCount() > 0) { user.setLastModifyTime(lastModifyTime); LOG.info("Successful to change password '{}'", user.getName()); } else { throw new NotStoredException("Can't find user account '" + user.getId() + "'"); } LOG.info("Successful to change password '{}'", user.getName()); } catch (MongoException e) { LOG.error("Failed to change password", e); throw new MetaStoreException("Failed to change password", e); } }
From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java
License:Apache License
@Override public boolean changeSchemasToUsed(Schema schema, String topologyId) throws MetaStoreException { if (!ObjectId.isValid(schema.getId())) { throw new MetaStoreException("Invalid schema ID '" + schema.getId() + "'"); }//from w w w . jav a 2 s .c o m try { UpdateResult result = schemaCollection.updateOne( and(eq("_id", new ObjectId(schema.getId())), eq("createTime", schema.getCreateTime())), new Document("$push", new Document("topologies", topologyId))); if (result.getModifiedCount() > 0) { LOG.info("Successful to change to busy schema {} owned by {}", schema.getSchemaName(), schema.getOwner().getName()); return true; } else { return false; } } catch (MongoException e) { LOG.error("Failed to change to free schema {} owned by {}", schema.getSchemaName(), schema.getOwner().getName(), e); throw new MetaStoreException("Failed to busy schemas", e); } }
From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java
License:Apache License
@Override public boolean changeSchemasToFree(Schema schema, String topologyId) throws MetaStoreException { if (!ObjectId.isValid(schema.getId())) { throw new MetaStoreException("Invalid schema ID '" + schema.getId() + "'"); }//from ww w . j a va 2 s .co m try { UpdateResult result = schemaCollection.updateOne( and(eq("_id", new ObjectId(schema.getId())), eq("createTime", schema.getCreateTime())), new Document("$pull", new Document("topologies", topologyId))); if (result.getModifiedCount() > 0) { LOG.info("Successful to change to free schema {} owned by {}", schema.getSchemaName(), schema.getOwner().getName()); return true; } else { return false; } } catch (MongoException e) { LOG.error("Failed to change to free schema {} owned by {}", schema.getSchemaName(), schema.getOwner().getName(), e); throw new MetaStoreException("Failed to find schemas", e); } }
From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java
License:Apache License
@Override public boolean changeTopologyStatus(GungnirTopology topology) throws MetaStoreException { if (!ObjectId.isValid(topology.getId())) { throw new MetaStoreException("Invalid topology ID '" + topology.getId() + "'"); }//from w w w .ja v a2 s .c o m try { TopologyStatus status = null; switch (topology.getStatus()) { case STARTING: status = TopologyStatus.STOPPED; break; case RUNNING: status = TopologyStatus.STARTING; break; case STOPPING: status = TopologyStatus.RUNNING; break; case STOPPED: status = TopologyStatus.STOPPING; break; default: return false; } UpdateResult result = topologyCollection.updateOne( and(eq("_id", new ObjectId(topology.getId())), eq("status", status.toString())), new Document("$set", new Document("status", topology.getStatus().toString()))); if (result.getModifiedCount() > 0) { LOG.info("Successful to change topology status '{}' ({}->{})", topology.getId(), status, topology.getStatus()); return true; } else { return false; } } catch (MongoException e) { LOG.error("Failed to change topology status", e); throw new MetaStoreException("Failed to change topology status", e); } }
From source file:org.opencb.opencga.storage.mongodb.variant.adaptors.VariantMongoDBWriter.java
License:Apache License
@Override public boolean post() { // if (currentBulkSize != 0) { // executeBulk(); // }//from w w w. j a v a2 s . c om logger.debug("POST"); if (!variantSourceWritten.getAndSet(true)) { if (writeStudyConfiguration) { writeStudyConfiguration(); } // if (writeVariantSource) { // writeSourceSummary(source); // } List<Region> regions = coveredChromosomes.stream().map(Region::new).collect(Collectors.toList()); long nanoTime = System.nanoTime(); UpdateResult updateResult = dbAdaptor .fillFileGaps(fileId, new LinkedList<>(coveredChromosomes), fileSampleIds, studyConfiguration) .first(); if (updateResult != null) { writeResult.setUpdatedMissingVariants( writeResult.getUpdatedMissingVariants() + updateResult.getModifiedCount()); } writeResult.setFillGapsNanoTime(System.nanoTime() - nanoTime); dbAdaptor.createIndexes(new QueryOptions()); } // logger.debug("checkExistsTime " + checkExistsTime / 1000000.0 + "ms "); // logger.debug("checkExistsDBTime " + checkExistsDBTime / 1000000.0 + "ms "); // logger.debug("bulkTime " + bulkTime / 1000000.0 + "ms "); logger.debug("insertionTime " + insertionTime / 1000000.0 + "ms "); return true; }
From source file:org.opentdc.mongo.AbstractMongodbServiceProvider.java
License:Open Source License
/** * Update the database object with a given unique id. * @param id the unique identificator of the object to update * @param document the new data of the database object * @return the updated object containing the new data * @throws NotFoundException if no object with the given id was found * @throws InternalServerErrorException if there was a problem getting the object from mongodb *///from w ww .j a va2 s .co m protected void update(String id, Document document) throws NotFoundException, InternalServerErrorException { UpdateResult _result = null; try { logger.info("update(" + id + ", " + document.toJson() + ")"); _result = collection.updateOne(eq("_id", new ObjectId(id)), new Document("$set", document)); // TODO: better handling of UpdateResult } catch (Exception _ex) { logger.info(_ex.getMessage()); logger.info(_ex.getStackTrace().toString()); throw new InternalServerErrorException("could not update dbobject <" + id + ">"); } if (_result.getModifiedCount() == 0) { throw new NotFoundException( "dbobject with id <" + id + "> was not found in collection " + collectionName + "."); } logger.info("update(" + id + ", " + document.toJson() + ") -> OK"); }
From source file:org.restheart.db.DAOUtils.java
License:Open Source License
public static boolean restoreDocument(MongoCollection<BsonDocument> coll, Object documentId, BsonDocument shardKeys, BsonDocument data, Object etag) { Objects.requireNonNull(coll); Objects.requireNonNull(documentId); Objects.requireNonNull(data); Bson query;//from w w w.jav a 2 s. c o m if (etag == null) { query = eq("_id", documentId); } else { query = and(eq("_id", documentId), eq("_etag", etag)); } if (shardKeys != null) { query = and(query, shardKeys); } UpdateResult result = coll.replaceOne(query, data, U_NOT_UPSERT_OPS); if (result.isModifiedCountAvailable()) { return result.getModifiedCount() == 1; } else { return true; } }
From source file:service.MongoLanguageService.java
@Override public void update(Language language) { UpdateResult updateResult = collection.updateMany(lt("id", 100), inc("id", 100)); System.out.println(updateResult.getModifiedCount()); // collection.updateOne( // eq("_id", new ObjectId("57506d62f57802807471dd41")), // combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified"))); }
From source file:tour.PojoQuickTour.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 2 s .c om*/ public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = MongoClients.create(); } else { mongoClient = MongoClients.create(args[0]); } // create codec registry for POJOs CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build())); // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry); // get a handle to the "people" collection MongoCollection<Person> collection = database.getCollection("people", Person.class); // drop all the data in it collection.drop(); // make a document and insert it Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1")); System.out.println("Original Person Model: " + ada); collection.insertOne(ada); // Person will now have an ObjectId System.out.println("Mutated Person Model: " + ada); // get it (since it's the only one in there since we dropped the rest earlier on) Person somebody = collection.find().first(); System.out.println(somebody); // now, lets add some more people so we can explore queries and cursors List<Person> people = asList( new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))); collection.insertMany(people); System.out.println("total # of people " + collection.countDocuments()); System.out.println(""); // lets get all the documents in the collection and print them out Block<Person> printBlock = new Block<Person>() { @Override public void apply(final Person person) { System.out.println(person); } }; collection.find().forEach(printBlock); System.out.println(""); // now use a query to get 1 document out somebody = collection.find(eq("address.city", "Wimborne")).first(); System.out.println(somebody); System.out.println(""); // now lets find every over 30 collection.find(gt("age", 30)).forEach(printBlock); System.out.println(""); // Update One collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace"))); System.out.println(""); // Update Many UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null)); System.out.println(updateResult.getModifiedCount()); System.out.println(""); // Replace One updateResult = collection.replaceOne(eq("name", "Ada Lovelace"), ada); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("address.city", "Wimborne")); // Delete Many DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London")); System.out.println(deleteResult.getDeletedCount()); // Clean up database.drop(); // release resources mongoClient.close(); }
From source file:uk.ac.ebi.eva.dbmigration.mongodb.ExtractAnnotationFromVariant.java
License:Apache License
@ChangeSet(order = "006", id = "addDefaultVersionInAnnotationMetadata", author = "EVA") public void addDefaultVersion(MongoDatabase mongoDatabase) { final MongoCollection<Document> annotationMetadataCollection = mongoDatabase .getCollection(databaseParameters.getDbCollectionsAnnotationMetadataName()); logger.info("6) add default annotation version to collection {} ", annotationMetadataCollection.getNamespace()); Document allVersions = new Document(); Document setDefaultToFalse = new Document("$set", new Document(DEFAULT_VERSION_FIELD, false)); annotationMetadataCollection.updateMany(allVersions, setDefaultToFalse); String id = databaseParameters.getVepVersion() + "_" + databaseParameters.getVepCacheVersion(); Document defaultVersionDocument = new Document(ID_FIELD, id); Document setDefaultToTrue = new Document("$set", new Document(DEFAULT_VERSION_FIELD, true)); UpdateResult updateResult = annotationMetadataCollection.updateOne(defaultVersionDocument, setDefaultToTrue);//from w w w. ja va2 s . co m Assert.state(updateResult.getModifiedCount() == 1, "Only one modification was expected"); }