List of usage examples for com.mongodb DBCollection update
public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi, final WriteConcern aWriteConcern)
From source file:org.hibernate.ogm.datastore.mongodb.MongoDBDialect.java
License:LGPL
@Override public void insertOrUpdateAssociation(AssociationKey key, Association association, AssociationContext associationContext) { DBCollection collection; DBObject query;/*w w w . j a v a2s. c o m*/ MongoDBAssociationSnapshot assocSnapshot = (MongoDBAssociationSnapshot) association.getSnapshot(); String associationField; AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy(key, associationContext); WriteConcern writeConcern = getWriteConcern(associationContext); List<?> rows = getAssociationRows(association, key); Object toStore = key.getMetadata().isOneToOne() ? rows.get(0) : rows; if (storageStrategy == AssociationStorageStrategy.IN_ENTITY) { collection = this.getCollection(key.getEntityKey()); query = this.prepareIdObject(key.getEntityKey()); associationField = key.getMetadata().getCollectionRole(); //TODO would that fail if getCollectionRole has dots? ((MongoDBTupleSnapshot) associationContext.getEntityTuple().getSnapshot()).getDbObject() .put(key.getMetadata().getCollectionRole(), toStore); } else { collection = getAssociationCollection(key, storageStrategy); query = assocSnapshot.getQueryObject(); associationField = ROWS_FIELDNAME; } DBObject update = new BasicDBObject("$set", new BasicDBObject(associationField, toStore)); collection.update(query, update, true, false, writeConcern); }
From source file:org.jumpmind.symmetric.io.MongoDatabaseWriter.java
License:Open Source License
protected LoadStatus upsert(CsvData data) { statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS); try {/*from w w w .j av a2 s. co m*/ DB db = clientManager.getDB(objectMapper.mapToDatabase(this.targetTable)); DBCollection collection = db.getCollection(objectMapper.mapToCollection(this.targetTable)); String[] columnNames = sourceTable.getColumnNames(); Map<String, String> newData = data.toColumnNameValuePairs(columnNames, CsvData.ROW_DATA); Map<String, String> oldData = data.toColumnNameValuePairs(columnNames, CsvData.OLD_DATA); Map<String, String> pkData = data.toKeyColumnValuePairs(this.sourceTable); DBObject query = objectMapper.mapToDBObject(sourceTable, newData, oldData, pkData, true); DBObject object = objectMapper.mapToDBObject(sourceTable, newData, oldData, pkData, false); WriteResult results = collection.update(query, object, true, false, WriteConcern.ACKNOWLEDGED); if (results.getN() == 1) { return LoadStatus.SUCCESS; } else { throw new SymmetricException("Failed to write data: " + object.toString()); } } finally { statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS); } }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
@SuppressWarnings("finally") private boolean countRawTarget(StatEvent event) throws StatsEngineException { boolean processed = false; try {/*from w w w . j a va 2s .c o m*/ BasicDBObject q = new BasicDBObject(); q.put(EVENT_CLIENT_ID, event.getClientId()); q.put(EVENT_TARGET, event.getTarget()); q.put(EVENT_TARGET_TYPE, event.getTargetType()); q.put(EVENT_ACTION, event.getAction()); q.put(EVENT_DATE, event.getYearMonthDate().toDate()); q.put(TARGET_YEAR, event.getYear()); q.put(TARGET_MONTH, event.getMonth()); BasicDBObject doc = new BasicDBObject(); //BasicDBObject docSet = new BasicDBObject(); doc.put("$addToSet", createAddToSetOwnersTagsDoc(event)); BasicDBObject incDoc = new BasicDBObject(); incDoc.put(FIELD_COUNT, 1); //Month count String metaBaseKey = ""; TimeScope precision = getTimeScopePrecision(); if (precision == TimeScope.DAILY || precision == TimeScope.HOURLY) { String dayKey = createDotPath(FIELD_DAYS, event.getDay()); incDoc.put(createDotPath(dayKey, FIELD_COUNT), 1); //Day count if (precision == TimeScope.HOURLY) { String hourKey = createDotPath(dayKey, FIELD_HOURS, event.getHour()); incDoc.put(createDotPath(hourKey, FIELD_COUNT), 1);//Hour count metaBaseKey = hourKey; } else { metaBaseKey = dayKey; } } //Count metadata Map<String, Object> metadata = event.getMetadata(); for (String metaKey : metadata.keySet()) { incDoc.put(createDotPath(metaBaseKey, FIELD_META, metaKey, metaKeyValue(metaKey, metadata.get(metaKey))), 1); } doc.put("$inc", incDoc); DBCollection targets = getTargetCollection(event, TimeScope.GLOBAL); //TODO externalize write concern to configuration properties: WriteResult wr = targets.update(q, doc, true, true, WriteConcern.FSYNC_SAFE); processed = wr.getN() > 0; } catch (MongoException ex) { int errorCode = ex.getCode(); if (errorCode == ERROR_DUPKEY || errorCode == ERROR_DUPKEY_INSERT) { throw new DuplicateEventException("Duplicate event " + event); } throw new StatsEngineException("countRawTarget failed", ex); } return processed; }
From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreMixin.java
License:Apache License
@Override public void applyChanges(MapChanges changes) throws IOException { db.requestStart();//from w w w. j a v a2 s . c om final DBCollection entities = db.getCollection(collectionName); changes.visitMap(new MapChanger() { @Override public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException { return new StringWriter(1000) { @Override public void close() throws IOException { super.close(); String jsonState = toString(); System.out.println("############################################"); try { System.out.println(new JSONObject(jsonState).toString(2)); } catch (JSONException ex) { ex.printStackTrace(); } System.out.println("############################################"); DBObject bsonState = (DBObject) JSON.parse(jsonState); BasicDBObject entity = new BasicDBObject(); entity.put(IDENTITY_COLUMN, ref.identity()); entity.put(STATE_COLUMN, bsonState); entities.save(entity, writeConcern); } }; } @Override public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException { return new StringWriter(1000) { @Override public void close() throws IOException { super.close(); DBObject bsonState = (DBObject) JSON.parse(toString()); BasicDBObject entity = new BasicDBObject(); entity.put(IDENTITY_COLUMN, ref.identity()); entity.put(STATE_COLUMN, bsonState); entities.update(byIdentity(ref), entity, true, false, writeConcern); } }; } @Override public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor) throws EntityNotFoundException { DBObject entity = entities.findOne(byIdentity(ref)); if (entity == null) { throw new EntityNotFoundException(ref); } entities.remove(entity, writeConcern); } }); db.requestDone(); }
From source file:org.s1.mongodb.cluster.MongoDBDDS.java
License:Apache License
@Override public void runWriteCommand(CommandBean b) { if (Objects.isNullOrEmpty(b.getCollection())) { return;/*from w ww . ja va 2 s .c o m*/ } if (Objects.isNullOrEmpty(b.getEntity())) { return; } DBCollection coll = MongoDBConnectionHelper.getConnection(b.getDatabase()).getCollection(b.getCollection()); if ("add".equals(b.getCommand()) || "set".equals(b.getCommand())) { if (b.getParams() == null) { return; } Map<String, Object> search = Objects.newHashMap("id", b.getEntity()); b.getParams().put("id", b.getEntity()); int n = coll.update(MongoDBFormat.fromMap(search), MongoDBFormat.fromMap(b.getParams()), b.getCommand().equals("add"), false, WriteConcern.FSYNC_SAFE).getN(); if (LOG.isDebugEnabled()) LOG.debug("MongoDB records(" + n + ") " + (b.getCommand().equals("add") ? "added" : "updated") + ", " + b); } else if ("remove".equals(b.getCommand())) { Map<String, Object> search = Objects.newHashMap("id", b.getEntity()); int n = coll.remove(MongoDBFormat.fromMap(search), WriteConcern.FSYNC_SAFE).getN(); if (LOG.isDebugEnabled()) LOG.debug("MongoDB records(" + n + ") removed, " + b); } }
From source file:org.s1.mongodb.cluster.MongoDBOperationLog.java
License:Apache License
@Override public void markDone(long id) { DBCollection coll = getCollection(); coll.update(new BasicDBObject("id", id), new BasicDBObject("$set", new BasicDBObject("done", true)), false, false, WriteConcern.FSYNC_SAFE); if (LOG.isDebugEnabled()) LOG.debug("Node write log record #" + id + " marked as done:true"); }
From source file:org.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java
License:Apache License
@Override public void performInsertion(final Collection<Item> items) { DBCollection meterCollection = mongoTemplate.getCollection("meter"); DBCollection sumsCollection = mongoTemplate.getCollection("sums"); for (Item item : items) { //some time calculations Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(item.getWhen()); cal.set(Calendar.MILLISECOND, 0); long second = cal.getTimeInMillis(); cal.set(Calendar.SECOND, 0); long minute = cal.getTimeInMillis(); cal.set(Calendar.MINUTE, 0); long hour = cal.getTimeInMillis(); cal.setTimeInMillis(item.getWhen()); BasicDBObject query = new BasicDBObject(); PathElements pathElements = MeterHit.calcPath(item.getPath(), "/"); query.append("id", integerForCompatibilityReasonOrString(pathElements.getE4())); query.append("sectionId", integerForCompatibilityReasonOrString(pathElements.getE3())); query.append("publicationId", integerForCompatibilityReasonOrString(pathElements.getE2())); query.append("type", pathElements.getE1()); StringBuilder sb = new StringBuilder(); sb.append("{ '$inc': "); sb.append(" { 'day.count' : " + item.getAccessNumber() + ", "); sb.append(" 'day.last15minutes' : " + item.getAccessNumber() + ", "); sb.append(" 'day.last180minutes' : " + item.getAccessNumber() + ", "); sb.append(" 'day.hours." + hour + ".count' : " + item.getAccessNumber() + ", "); sb.append(//from ww w . j a v a 2 s . c o m " 'day.hours." + hour + ".minutes." + minute + ".count' : " + item.getAccessNumber() + " "); sb.append("}}"); DBObject update = (DBObject) JSON.parse(sb.toString()); meterCollection.update(query, update, true, false, WriteConcern.UNACKNOWLEDGED); query = new BasicDBObject(); BasicDBObject time = new BasicDBObject(); query.append("time", time); time.append("ts", minute); time.append("year", cal.get(Calendar.YEAR)); time.append("month", cal.get(Calendar.MONTH)); time.append("day", cal.get(Calendar.DAY_OF_MONTH)); time.append("hour", cal.get(Calendar.HOUR_OF_DAY)); time.append("minute", cal.get(Calendar.MINUTE)); sb = new StringBuilder(); sb.append(" { '$inc': "); sb.append("{ 'total' : ").append(item.getAccessNumber()); if (pathElements.getE1().equals("article")) { sb.append(", 'article' : ").append(item.getAccessNumber()); } else if (pathElements.getE1().equals("album")) { sb.append(", 'album' : ").append(item.getAccessNumber()); } else if (pathElements.getE1().equals("video")) { sb.append(", 'video' : ").append(item.getAccessNumber()); } else { sb.append(", 'other' : ").append(item.getAccessNumber()); } sb.append(" } }"); update = (DBObject) JSON.parse(sb.toString()); sumsCollection.update(query, update, true, false, WriteConcern.UNACKNOWLEDGED); } }
From source file:org.socialhistoryservices.security.MongoUserDetailService.java
License:Open Source License
public void createUser(MongoUserDetails user) { if (user.getPassword() != null) user.setPassword(HashPassword.encrypt(HASH, user.getPassword())); final DBCollection coll = coll(); BasicDBObject query = new BasicDBObject("username", user.getUsername()); DBObject tmp = coll.findOne(query);// w w w. jav a 2 s . c o m if (tmp != null) { if (user.getPassword() == null) { user.setPassword((String) tmp.get("password")); } if (user.getAuthorities().size() == 0) { BasicDBList authorities = (BasicDBList) tmp.get("authorities"); for (Object authority : authorities) { user.getAuthorities() .add(new org.socialhistoryservices.security.MongoAuthority((String) authority)); } } } BasicDBObject document = new BasicDBObject(); document.put("username", user.getUsername()); document.put("password", user.getPassword()); document.put("enabled", user.isEnabled()); document.put("accountNonExpired", user.isAccountNonExpired()); document.put("accountNonLocked", user.isAccountNonLocked()); document.put("credentialsNonExpired", user.isCredentialsNonExpired()); BasicDBList authorities = new BasicDBList(); for (GrantedAuthority authority : user.getAuthorities()) { authorities.add(authority.getAuthority()); } document.put("authorities", authorities); final WriteResult result = coll.update(query, document, true, false, WriteConcern.SAFE); if (result.getN() == 0) log.error(new Exception("Adding the user failed: " + result.getError())); log.info("Persisted:\n" + document.toString()); }
From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java
License:Apache License
@Override public void updateEntry(final PersistentEntity persistentEntity, final Object key, final DBObject entry) { mongoTemplate.execute(new DbCallback<Object>() { @Override//from ww w . j a v a2 s .c om public Object doInDB(DB con) throws MongoException, DataAccessException { String collectionName = getCollectionName(persistentEntity, entry); DBCollection dbCollection = con.getCollection(collectionName); DBObject dbo = new BasicDBObject(); if (hasNumericalIdentifier) { dbo.put(MONGO_ID_FIELD, key); } else { dbo.put(MONGO_ID_FIELD, new ObjectId(key.toString())); } MongoSession mongoSession = (MongoSession) session; dbCollection.update(dbo, entry, false, false, mongoSession.getWriteConcern()); return null; } }); }
From source file:org.teiid.translator.mongodb.MongoDBUpdateExecution.java
License:Open Source License
private void executeInternal() throws TranslatorException { DBCollection collection = getCollection(this.visitor.mongoDoc.getTargetTable()); MongoDocument mongoDoc = this.visitor.mongoDoc; AggregationOptions options = this.executionFactory.getOptions(this.executionContext.getBatchSize()); List<WriteResult> executionResults = new ArrayList<WriteResult>(); if (this.command instanceof Insert) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); // check if this document need to be embedded in any other document if (mongoDoc.isMerged()) { DBObject match = getInsertMatch(mongoDoc, this.visitor.columnValues); BasicDBObject insert = this.visitor.getInsert(embeddedDocuments); if (mongoDoc.getMergeKey().getAssociation() == Association.MANY) { removeParentKey(mongoDoc, insert); BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$push\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$push", insertDoc), false, //$NON-NLS-1$ true, WriteConcern.ACKNOWLEDGED)); } else { insert.remove("_id"); //$NON-NLS-1$ BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", insertDoc), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); }//from www . j ava 2 s. com } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } // gets its own collection BasicDBObject in = this.visitor.getInsert(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "{\"insert\": {" + in + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.insert(in, WriteConcern.ACKNOWLEDGED)); } } else if (this.command instanceof Update) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isMerged()) { // multi items in array update not available, http://jira.mongodb.org/browse/SERVER-1243 // this work-around for above issue List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new UpdateOperationImpl()); } } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } BasicDBObject u = this.visitor.getUpdate(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + u + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", u), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); } // if the update is for the "embeddable" table, then since it is copied to other tables // those references need to be updated. I know this is not atomic operation, but not sure // how else to handle it. if (mongoDoc.isEmbeddable()) { updateReferenceTables(collection, mongoDoc, match, options); } } else { // Delete DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isEmbeddable()) { DBObject m = new BasicDBObject("$match", match); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(m), options); while (output.hasNext()) { DBObject row = output.next(); if (row != null) { for (MergeDetails ref : mongoDoc.getEmbeddedIntoReferences()) { DBCollection parent = getCollection(ref.getParentTable()); DBObject parentMatch = buildParentMatch(row, ref); DBObject refMatch = new BasicDBObject("$match", parentMatch); //$NON-NLS-1$ Cursor referenceOutput = parent.aggregate(Arrays.asList(refMatch), options); if (referenceOutput.hasNext()) { throw new TranslatorException(MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18010, this.visitor.mongoDoc.getTargetTable().getName(), ref.getParentTable())); } } } } } if (mongoDoc.isMerged()) { List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new DeleteOperationImpl(match)); } } else { LogManager.logDetail(LogConstants.CTX_CONNECTOR, "remove - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.remove(match, WriteConcern.ACKNOWLEDGED)); } } if (!executionResults.isEmpty()) { if (this.command instanceof Insert) { if (this.executionContext.getCommandContext().isReturnAutoGeneratedKeys()) { addAutoGeneretedKeys(executionResults.get(0)); } } int updated = 0; for (WriteResult result : executionResults) { updated += result.getN(); } this.results = new int[1]; this.results[0] = updated; } }