List of usage examples for com.mongodb DBCollection update
public WriteResult update(final DBObject query, final DBObject update)
From source file:net.scran24.datastore.mongodb.MongoDbDataStore.java
License:Apache License
@Override public void setUserData(String survey_id, String user_id, Map<String, String> userData) throws DataStoreException { DBCollection usersCollection = getUsersCollection(survey_id); BasicDBObject newUserData = new BasicDBObject(); for (String k : userData.keySet()) newUserData.append(k, userData.get(k)); usersCollection.update(new BasicDBObject(FIELD_USERNAME, user_id), new BasicDBObject("$set", new BasicDBObject(FIELD_USERDATA, newUserData))); }
From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoDB.java
License:Open Source License
/** * Updates a document in the database./* w w w.ja v a 2 s . co m*/ */ public void update(DBCollection collection, DBObject query, DBObject document) throws UpdateException, StorageException { try { WriteResult writeResult = collection.update(query, document); if (writeResult.getN() == 0) { LOG.error("Failed to update {}", query); throw new UpdateException("Update failed"); } } catch (MongoException e) { throw new StorageException(e); } }
From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java
/** * Saves a single Parachuteobject to mongoDB * /* w w w. j a v a 2 s . c o m*/ * @param parachutist */ public void addJumperToDb(Parachutist parachutist) { DBCollection dbCollectionParachutistsCount = db.getCollection("jumpercounter"); DBCollection dbCollectionParachutists = db.getCollection("jumpers"); BasicDBObject incrementJumpcount = new BasicDBObject().append("$inc", new BasicDBObject().append("seq", 1)); BasicDBObject query = new BasicDBObject("_id", "jumperCount"); int countInt = (int) dbCollectionParachutistsCount.findOne().get("seq"); ArrayList<Integer> memberLicenses = new ArrayList<>(); for (License license : parachutist.getLicenses()) { memberLicenses.add(license.getId()); } ArrayList<Integer> memberClubs = new ArrayList<>(); for (Club club : parachutist.getMemberclubs()) { memberClubs.add(club.getId()); } dbCollectionParachutistsCount.update(query, incrementJumpcount); BasicDBObject parachutistMongoObject = new BasicDBObject("melwinId", parachutist.getMelwinId()) .append("_class", "no.nlf.models.mongoclasses.MongoParachutist").append("memberclubs", memberClubs) .append("licenses", memberLicenses).append("firstname", parachutist.getFirstname()) .append("lastname", parachutist.getLastname()).append("id", countInt + 1) .append("birthdate", parachutist.getBirthdate()).append("gender", parachutist.getGender()) .append("street", parachutist.getStreet()).append("postnumber", parachutist.getPostnumber()) .append("postplace", parachutist.getPostplace()).append("mail", parachutist.getMail()) .append("phone", parachutist.getPhone()); dbCollectionParachutists.save(parachutistMongoObject); }
From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java
public void updateJumperinDb(Parachutist parachutist) { DBCollection dbCollectionParachutists = db.getCollection("jumpers"); ArrayList<Integer> memberLicenses = new ArrayList<>(); for (License license : parachutist.getLicenses()) { memberLicenses.add(license.getId()); }// w w w. j a v a 2s. c o m ArrayList<Integer> memberClubs = new ArrayList<>(); for (Club club : parachutist.getMemberclubs()) { memberClubs.add(club.getId()); } BasicDBObject mongojumper = new BasicDBObject("melwinId", parachutist.getMelwinId()) .append("memberclubs", memberClubs).append("id", parachutist.getId()) .append("licenses", memberLicenses).append("firstname", parachutist.getFirstname()) .append("lastname", parachutist.getLastname()).append("birthdate", parachutist.getBirthdate()) .append("gender", parachutist.getGender()).append("street", parachutist.getStreet()) .append("postnumber", parachutist.getPostnumber()).append("postplace", parachutist.getPostplace()) .append("mail", parachutist.getMail()).append("phone", parachutist.getPhone()); BasicDBObject searchQuery = new BasicDBObject().append("id", parachutist.getId()); dbCollectionParachutists.update(searchQuery, mongojumper); }
From source file:org.alfresco.extension.wcmdeployment.mongodb.MongoDbDeploymentTarget.java
License:Open Source License
private void setVersion(final DB database, final int version) { if (database != null) { DBCollection collection = database.getCollection("deploymentSystem"); DBObject query = new BasicDBObject(); DBObject statement = new BasicDBObject(); query.put("_id", "version"); statement.put("$set", new BasicDBObject("version", version)); collection.update(query, statement); }/* w w w. j a va 2 s . c om*/ }
From source file:org.apache.camel.component.mongodb.MongoDbProducer.java
License:Apache License
@SuppressWarnings("unchecked") protected void doUpdate(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); List<DBObject> saveObj = exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class); if (saveObj.size() != 2) { throw new CamelMongoDbException( "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2"); }//from w w w. j av a2s. c om DBObject updateCriteria = saveObj.get(0); DBObject objNew = saveObj.get(1); Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class); Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class); WriteResult result; WriteConcern wc = extractWriteConcern(exchange); // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false, false, so we unconditionally invoke the // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default behaviour may change in the future, // so it's safer to be explicit at this level for full determinism if (multi == null && upsert == null) { // for update with no multi nor upsert but with specific WriteConcern there is no update signature without multi and upsert args, // so assume defaults result = wc == null ? dbCol.update(updateCriteria, objNew) : dbCol.update(updateCriteria, objNew, false, false, wc); } else { // we calculate the final boolean values so that if any of these // parameters is null, it is resolved to false result = wc == null ? dbCol.update(updateCriteria, objNew, calculateBooleanValue(upsert), calculateBooleanValue(multi)) : dbCol.update(updateCriteria, objNew, calculateBooleanValue(upsert), calculateBooleanValue(multi), wc); } Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update); // we always return the WriteResult, because whether the getLastError was called or not, the user will have the means to call it or // obtain the cached CommandResult processAndTransferWriteResult(result, exchange); resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN()); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java
License:Apache License
@SuppressWarnings("unchecked") @CheckForNull/*from w ww . j a v a2s. c o m*/ private <T extends Document> T findAndModify(Collection<T> collection, UpdateOp updateOp, boolean upsert, boolean checkConditions) { DBCollection dbCollection = getDBCollection(collection); // make sure we don't modify the original updateOp updateOp = updateOp.copy(); DBObject update = createUpdate(updateOp, false); Lock lock = null; if (collection == Collection.NODES) { lock = nodeLocks.acquire(updateOp.getId()); } final Stopwatch watch = startWatch(); boolean newEntry = false; try { // get modCount of cached document Long modCount = null; T cachedDoc = null; if (collection == Collection.NODES) { cachedDoc = (T) nodesCache.getIfPresent(updateOp.getId()); if (cachedDoc != null) { modCount = cachedDoc.getModCount(); } } // perform a conditional update with limited result // if we have a matching modCount if (modCount != null) { QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); query.and(Document.MOD_COUNT).is(modCount); WriteResult result = dbCollection.update(query.get(), update); if (result.getN() > 0) { // success, update cached document if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, cachedDoc, updateOp); nodesCache.put(newDoc); } // return previously cached document return cachedDoc; } } // conditional update failed or not possible // perform operation and get complete document QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); DBObject oldNode = dbCollection.findAndModify(query.get(), null, null /*sort*/, false /*remove*/, update, false /*returnNew*/, upsert); if (oldNode == null) { newEntry = true; } if (checkConditions && oldNode == null) { return null; } T oldDoc = convertFromDBObject(collection, oldNode); if (oldDoc != null) { if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, oldDoc, updateOp); nodesCache.put(newDoc); updateLocalChanges(newDoc); } oldDoc.seal(); } else if (upsert) { if (collection == Collection.NODES) { NodeDocument doc = (NodeDocument) collection.newDocument(this); UpdateUtils.applyChanges(doc, updateOp); nodesCache.putIfAbsent(doc); updateLocalChanges(doc); } } else { // updateOp without conditions and not an upsert // this means the document does not exist } return oldDoc; } catch (Exception e) { throw DocumentStoreException.convert(e); } finally { if (lock != null) { lock.unlock(); } stats.doneFindAndModify(watch.elapsed(TimeUnit.NANOSECONDS), collection, updateOp.getId(), newEntry, true, 0); } }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStoreHelper.java
License:Apache License
public static void repair(MongoDocumentStore store, String path) { DBCollection col = store.getDBCollection(NODES); String id = Utils.getIdFromPath(path); NodeDocument doc = store.find(NODES, id); if (doc == null) { System.out.println("No document for path " + path); return;/*from w w w. ja v a 2s .c o m*/ } Set<Revision> changes = Sets.newHashSet(); for (String key : doc.keySet()) { if (Utils.isPropertyName(key) || NodeDocument.isDeletedEntry(key)) { changes.addAll(getLocalMap(doc, key).keySet()); } } SortedMap<Revision, String> commitRoot = newTreeMap(getLocalCommitRoot(doc)); if (!commitRoot.keySet().retainAll(changes)) { System.out.println("Nothing to repair on " + path); return; } Number modCount = doc.getModCount(); if (modCount == null) { System.err.println("Document does not have a modCount " + path); return; } DBObject query = QueryBuilder.start(Document.ID).is(id).and(Document.MOD_COUNT).is(modCount).get(); DBObject cr = new BasicDBObject(); for (Map.Entry<Revision, String> entry : commitRoot.entrySet()) { cr.put(entry.getKey().toString(), entry.getValue()); } DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject(commitRoot(), cr)); update.put("$inc", new BasicDBObject(Document.MOD_COUNT, 1L)); WriteResult result = col.update(query, update); if (result.getN() == 1) { int num = getLocalCommitRoot(doc).size() - commitRoot.size(); System.out.println("Removed " + num + " _commitRoot entries on " + path); } else { System.out.println("Unable to repair " + path + " (concurrent update)."); } }
From source file:org.apache.karaf.jaas.modules.mongo.internal.DefaultUserDetailService.java
License:Apache License
@Override public UserInfo addUser(UserInfo user) throws Exception { DB db = getDB();//from ww w.j a v a 2s.co m DBCollection users = db.getCollection(configuration.getUserCollectionName()); DBCollection roles = db.getCollection(configuration.getGroupCollectionName()); DBObject storedUser = users.findOne(new BasicDBObject().append("username", user.getName())); if (storedUser == null) { users.insert(BasicDBObjectBuilder.start("username", user.getName()) .append("passwordHash", user.getPassword()).get()); } else { // will not do anything here } for (String role : user.getGroups()) { DBObject roleQuery = new BasicDBObject("name", role); // roles are unique by name DBObject roleData = roles.findOne(roleQuery, ROLE_PROJECTION); if (roleData == null) { // add role with user as first member BasicDBList members = new BasicDBList(); members.add(user.getName()); roleData = BasicDBObjectBuilder.start().add("name", role).add("members", members).get(); roles.insert(roleData); } else { // add user to group if not already in the role's member list Object mo = roleData.get("members"); if (mo == null) { // TODO what here? BasicDBObject updateObject = new BasicDBObject().append("$push", new BasicDBObject("members", user.getName())); roles.update(roleQuery, updateObject); } else if (mo != null && mo instanceof List) { // if user is in group already we dont need to do anything List<?> existingMembers = (List<?>) mo; if (!existingMembers.contains(user.getName())) { // push this user to the members list BasicDBObject updateObject = new BasicDBObject().append("$push", new BasicDBObject("members", user.getName())); roles.update(roleQuery, updateObject); } } else { log.warn("The members collection of group [{}] is not a list but of type [{}].", role, mo.getClass().getName()); } } } return user; }
From source file:org.apache.rya.mongodb.instance.MongoRyaInstanceDetailsRepository.java
License:Apache License
@Override public void update(final RyaDetails oldDetails, final RyaDetails newDetails) throws NotInitializedException, ConcurrentUpdateException, RyaDetailsRepositoryException { // Preconditions. requireNonNull(oldDetails);/*from w w w. j a va2s . c o m*/ requireNonNull(newDetails); if (!newDetails.getRyaInstanceName().equals(instanceName)) { throw new RyaDetailsRepositoryException( "The instance name that was in the provided 'newDetails' does not match " + "the instance name that this repository is connected to. Make sure you're connected to the" + "correct Rya instance."); } if (!isInitialized()) { throw new NotInitializedException("Could not update the details for the Rya instanced named '" + instanceName + "' because it has not been initialized yet."); } if (oldDetails.equals(newDetails)) { return; } final DBCollection col = db.getCollection(INSTANCE_DETAILS_COLLECTION_NAME); final DBObject oldObj = MongoDetailsAdapter.toDBObject(oldDetails); final DBObject newObj = MongoDetailsAdapter.toDBObject(newDetails); final WriteResult result = col.update(oldObj, newObj); //since there is only 1 document, there should only be 1 update. if (result.getN() != 1) { throw new ConcurrentUpdateException("Could not update the details for the Rya instance named '" + instanceName + "' because the old value is out of date."); } }