Java Code Examples for com.mongodb.client.MongoCollection#findOneAndUpdate()
The following examples show how to use
com.mongodb.client.MongoCollection#findOneAndUpdate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoDbDAO.java From MtgDesktopCompanion with GNU General Public License v3.0 | 7 votes |
private Object getNextSequence() { MongoCollection<Document> countersCollection = db.getCollection("idSequences"); if (countersCollection.countDocuments() == 0) { createCountersCollection(countersCollection); } Document searchQuery = new Document("_id", "stock_increment"); Document increase = new Document("seq", 1); Document updateQuery = new Document("$inc", increase); Document result = countersCollection.findOneAndUpdate(searchQuery, updateQuery); return result.get("seq"); }
Example 2
Source File: ResourceDAO.java From SI with BSD 2-Clause "Simplified" License | 7 votes |
public void updateDocument(String keyName, String keyValue, HashMap<String, Object> map) { BasicDBObject query = new BasicDBObject(keyName, keyValue); Iterator<String> keys = map.keySet().iterator(); BasicDBObject param = new BasicDBObject(); while (keys.hasNext()) { String key = keys.next(); param.append(key, map.get(key)); } BasicDBObject update = new BasicDBObject(UPDATE_SPECIFIC_FIELD, param); MongoCollection<Document> collection = context.getDatabaseManager() .getCollection(collectionName); Document doc = collection.findOneAndUpdate(query, update); log.debug(doc.toString()); }
Example 3
Source File: DBusMongoClient.java From DBus with Apache License 2.0 | 6 votes |
public long nextSequence(String name) { MongoDatabase mdb = mongoClient.getDatabase("dbus"); MongoCollection mongoCollection = mdb.getCollection("dbus_sequence"); Document filter = new Document("_id", name); Document update = new Document("$inc", new Document("value", 1L)); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.upsert(true); options.returnDocument(ReturnDocument.AFTER); Document doc = (Document) mongoCollection.findOneAndUpdate(filter, update, options); return doc.getLong("value"); }
Example 4
Source File: DataSynchronizer.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Given a local collection, a document fetched from that collection, and its _id, ensure that * the document does not contain forbidden fields (currently just the document version field), * and remove them from the document and the local collection. If no changes are made, the * original document reference is returned. If changes are made, a cloned copy of the document * with the changes will be returned. * * @param localCollection the local MongoCollection from which the document was fetched * @param document the document fetched from the local collection. this argument may be mutated * @param documentId the _id of the fetched document (taken as an arg so that if the caller * already knows the _id, the document need not be traversed to find it) * @return a BsonDocument without any forbidden fields. */ private static BsonDocument sanitizeCachedDocument( final MongoCollection<BsonDocument> localCollection, final BsonDocument document, final BsonValue documentId ) { if (document == null) { return null; } if (document.containsKey(DOCUMENT_VERSION_FIELD)) { final BsonDocument clonedDoc = sanitizeDocument(document); final BsonDocument removeVersionUpdate = new BsonDocument("$unset", new BsonDocument(DOCUMENT_VERSION_FIELD, new BsonInt32(1)) ); localCollection.findOneAndUpdate(getDocumentIdFilter(documentId), removeVersionUpdate); return clonedDoc; } return document; }
Example 5
Source File: MongoCompensableLock.java From ByteTCC with GNU Lesser General Public License v3.0 | 6 votes |
private void initializeClusterInstanceVersion() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> instances = database.getCollection(CONSTANTS_TB_INSTS); Bson condition = Filters.eq("_id", this.endpoint); Document increases = new Document(); increases.append("version", 1L); Document document = new Document(); document.append("$inc", increases); Document target = instances.findOneAndUpdate(condition, document, new FindOneAndUpdateOptions().upsert(true)); this.instanceVersion = (target == null) ? 1 : (target.getLong("version") + 1); }
Example 6
Source File: ResourceDAO.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
public void updateDocument(String keyName, String keyValue, HashMap<String, Object> map) { BasicDBObject query = new BasicDBObject(keyName, keyValue); Iterator<String> keys = map.keySet().iterator(); BasicDBObject param = new BasicDBObject(); while (keys.hasNext()) { String key = keys.next(); param.append(key, map.get(key)); } BasicDBObject update = new BasicDBObject(UPDATE_SPECIFIC_FIELD, param); MongoCollection<Document> collection = context.getDatabaseManager() .getCollection(collectionName); Document doc = collection.findOneAndUpdate(query, update); log.debug(doc.toString()); }
Example 7
Source File: MongoCollectionFindAndModify.java From openbd-core with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings( "rawtypes" ) public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException { MongoDatabase db = getMongoDatabase( _session, argStruct ); String collection = getNamedStringParam(argStruct, "collection", null); if ( collection == null ) throwException(_session, "please specify a collection"); cfData update = getNamedParam(argStruct, "update", null ); if ( update == null ) throwException(_session, "please specify update"); cfData query = getNamedParam(argStruct, "query", null ); if ( query == null ) throwException(_session, "please specify query to update"); try{ MongoCollection<Document> col = db.getCollection(collection); FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions(); if ( getNamedParam(argStruct, "fields", null ) != null ) findOneAndUpdateOptions.projection( getDocument( getNamedParam(argStruct, "fields", null ) ) ); if ( getNamedParam(argStruct, "sort", null ) != null ) findOneAndUpdateOptions.sort( getDocument( getNamedParam(argStruct, "sort", null ) ) ); findOneAndUpdateOptions.upsert( getNamedBooleanParam(argStruct, "upsert", false ) ); if ( getNamedBooleanParam(argStruct, "returnnew", false ) ) findOneAndUpdateOptions.returnDocument( ReturnDocument.AFTER ); Document qry = getDocument(query); long start = System.currentTimeMillis(); Document result = col.findOneAndUpdate( qry, getDocument(update), findOneAndUpdateOptions ); _session.getDebugRecorder().execMongo(col, "findandmodify", qry, System.currentTimeMillis()-start); return tagUtils.convertToCfData( (Map)result ); } catch (MongoException me){ throwException(_session, me.getMessage()); return null; } }
Example 8
Source File: MongoCompensableLock.java From ByteTCC with GNU Lesser General Public License v3.0 | 5 votes |
private boolean relockTransactionInMongoDB(TransactionXid transactionXid, String identifier) { byte[] global = transactionXid.getGlobalTransactionId(); String instanceId = ByteUtils.byteArrayToString(global); try { String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS); Bson condition = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId); Document increases = new Document(); increases.append("times", 1); Document document = new Document(); document.append("$inc", increases); collection.findOneAndUpdate(condition, document, new FindOneAndUpdateOptions().upsert(true)); return true; } catch (com.mongodb.MongoWriteException error) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, error); return false; } catch (RuntimeException rex) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex); return false; } }
Example 9
Source File: MongoCompensableLock.java From ByteTCC with GNU Lesser General Public License v3.0 | 5 votes |
public boolean reExitTransactionInMongoDB(TransactionXid transactionXid, String identifier) { byte[] global = transactionXid.getGlobalTransactionId(); String instanceId = ByteUtils.byteArrayToString(global); try { String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS); Bson condition = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId); Document increases = new Document(); increases.append("times", -1); Document document = new Document(); document.append("$inc", increases); Document target = collection.findOneAndUpdate(condition, document, new FindOneAndUpdateOptions().upsert(true)); Integer times = target == null ? null : target.getInteger("times"); return times == null ? true : times <= 0; } catch (com.mongodb.MongoWriteException error) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, error); return true; } catch (RuntimeException rex) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex); return true; } }
Example 10
Source File: MongoClientTemplet.java From mongodb-orm with Apache License 2.0 | 5 votes |
private <T> T findAndModify(String statement, Object parameter, ResultHandler handler, boolean upsert) { if (logger.isDebugEnabled()) { logger.debug("Execute 'findAndModify' mongodb command. Statement '" + statement + "'."); } UpdateConfig config = (UpdateConfig) configuration.getStatement(statement); if (config == null) { throw new MongoDaoException(statement, "FindAndModify statement id '" + statement + "' not found."); } String collection = config.getCollection(); NodeEntry query = config.getQuery(); NodeEntry action = config.getAction(); NodeEntry field = config.getField(); MongoDatabase db = getDatabase(); MongoCollection<Document> coll = db.getCollection(collection); Map<String, Object> q = (Map<String, Object>) query.executorNode(config.getNamespace(), configuration, parameter); Map<String, Object> a = (Map<String, Object>) action.executorNode(config.getNamespace(), configuration, parameter); Map<String, Object> f = (Map<String, Object>) field.executorNode(config.getNamespace(), configuration, parameter); Document filter = new Document(q); Document update = (a == null) ? null : new Document(a); Document fieldDbo = (f == null) ? null : new Document(f); if (logger.isDebugEnabled()) { logger.debug("Execute 'findAndModify' mongodb command. Query '" + filter + "'."); logger.debug("Execute 'findAndModify' mongodb command. Action '" + update + "'."); logger.debug("Execute 'findAndModify' mongodb command. Field '" + fieldDbo + "'."); } Document document = coll.findOneAndUpdate(filter, update, new FindOneAndUpdateOptions().upsert(upsert)); if (logger.isDebugEnabled()) { logger.debug("Execute 'findAndModify' mongodb command. Result is '" + document + "'."); } if (handler != null) { handler.handleResult(new ResultContext() { @Override public Object getResultObject() { return document; } @Override public int getResultCount() { if (document == null) { return 0; } return 1; } }); return null; } return (T) helper.toResult(config.getNamespace(), field, document); }