Example usage for com.mongodb DBCollection update

List of usage examples for com.mongodb DBCollection update

Introduction

In this page you can find the example usage for com.mongodb DBCollection update.

Prototype

public WriteResult update(final DBObject query, final DBObject update, final boolean upsert,
        final boolean multi) 

Source Link

Document

Modify an existing document or documents in collection.

Usage

From source file:org.graylog2.database.MongoBridge.java

License:Open Source License

public void writeThroughput(int current, int highest) {
    BasicDBObject query = new BasicDBObject();
    query.put("type", "total_throughput");

    BasicDBObject update = new BasicDBObject();
    update.put("type", "total_throughput");
    update.put("current", current);
    update.put("highest", highest);

    DBCollection coll = MongoConnection.getInstance().getDatabase().getCollection("server_values");
    coll.update(query, update, true, false);
}

From source file:org.graylog2.database.MongoBridge.java

License:Open Source License

public void setSimpleServerValue(String key, Object value) {
    BasicDBObject query = new BasicDBObject();
    query.put("type", key);

    BasicDBObject update = new BasicDBObject();
    update.put("value", value);
    update.put("type", key);

    DBCollection coll = MongoConnection.getInstance().getDatabase().getCollection("server_values");
    coll.update(query, update, true, false);
}

From source file:org.hibernate.ogm.dialect.mongodb.MongoDBDialect.java

License:Open Source License

@Override
public void updateAssociation(Association association, AssociationKey key) {
    DBCollection collection = getAssociationCollection(key);
    MongoDBAssociationSnapshot assocSnapshot = (MongoDBAssociationSnapshot) association.getSnapshot();
    DBObject query = assocSnapshot.getQueryObject();

    for (AssociationOperation action : association.getOperations()) {
        RowKey rowKey = action.getKey();
        Tuple rowValue = action.getValue();

        DBObject update = null;/*from   w  w  w. j a  v  a2  s.co m*/

        switch (action.getType()) {
        case CLEAR:
            update = new BasicDBObject("$set", new BasicDBObject(ROWS_FIELDNAME, Collections.EMPTY_LIST));
            break;
        case PUT_NULL:
        case PUT:
            update = putAssociationRowKey(rowKey, rowValue);
            break;
        case REMOVE:
            update = removeAssociationRowKey(assocSnapshot, rowKey);
            break;
        }

        if (update != null)
            collection.update(query, update, true, false);
    }
}

From source file:org.i3xx.step.clockmongo.service.impl.ClockPersistenceServiceImpl.java

License:Apache License

/**
 * @param nspc The namespace/*w ww  .  ja  v  a2  s  .c  o m*/
 * @param stmt The time statement
 * @param symbol The symbol to add
 */
public void addMapping(String nspc, String stmt, String symbol) {
    logger.trace("Adds the object nspc:{} symbol:{} stmt:{}", nspc, symbol, stmt);

    DBCollection col = ensureCollection(nspc, symbol);
    DBObject dbo = ensureObject(col, symbol);

    dbo.put("statement", stmt);

    col.update(symbolQuery(symbol), dbo, false, false);
}

From source file:org.jewzaam.mongo.command.MongoUpsertCommand.java

License:Open Source License

@Override
protected Result run() {
    if (upsert instanceof Prepareable) {
        ((Prepareable) upsert).prepare();
    }//from  ww  w  .j  a  v a 2 s . c  om

    String json = converter.toJson(upsert);

    DBObject dbObj;
    if (upsert instanceof DBObject) {
        dbObj = (DBObject) upsert;
    } else {
        dbObj = (DBObject) JSON.parse(json);
    }

    try {
        db.requestStart();
        DBCollection coll = db.getCollection(collectionName);

        if (dbObj.get("_id") != null) {
            BasicDBObject query = new BasicDBObject().append("_id", dbObj.get("_id"));

            return new Result(coll.update(query, dbObj, true, false));
        } else {
            return new Result(coll.insert(dbObj));
        }
    } finally {
        db.requestDone();
    }
}

From source file:org.jwebsocket.amq.AMQClusterFilter.java

License:Apache License

/**
 *
 * @param aContext/* w ww.  j av a2 s.c o  m*/
 * @param aInfo
 * @return
 * @throws Exception
 */
@Override
public Subscription addConsumer(ConnectionContext aContext, ConsumerInfo aInfo) throws Exception {
    if (!aContext.isNetworkConnection()) {
        String lDest = aInfo.getDestination().getQualifiedName();

        String lSelector = aInfo.getSelector();
        if (null == lSelector) {
            // do not process
            return super.addConsumer(aContext, aInfo);
        }
        int lAPos = lSelector.indexOf("'");
        if (-1 == lAPos) {
            // do not process
            return super.addConsumer(aContext, aInfo);
        }

        int lBPos = lSelector.indexOf("'", lAPos + 1);

        // the correlation id identifies a consumer
        String lCorrelationId = lSelector.substring(lAPos + 1, lBPos);
        for (String lClusterDest : mTargetDestinations) {
            if (lClusterDest.matches(lDest)) {
                String lDatabaseName = aInfo.getDestination().getPhysicalName();
                if (lDatabaseName.endsWith("_nodes")) {
                    // supporting server nodes
                    // the database name match the C2S topic name
                    lDatabaseName = lDatabaseName.substring(0, lDatabaseName.length() - 6);
                }
                if (!mCachedCollections.containsKey(lDatabaseName)) {
                    // getting the mongo db collection
                    DB lDatabase = mMongo.getDB(lDatabaseName);
                    // authenticating if required
                    if (mUsername != null && mPassword != null) {
                        lDatabase.authenticate(mUsername, mPassword.toCharArray());
                    }
                    // caching collection instance
                    mCachedCollections.put(lDatabaseName, lDatabase.getCollection(COLLECTION_NAME));
                    // setting the collection as capped to ensure data expiration
                    lDatabase.command(new BasicDBObject().append("convertToCapped", COLLECTION_NAME)
                            .append("max", 1000000));
                }

                // getting cached collection instance
                DBCollection lCollection = mCachedCollections.get(lDatabaseName);
                DBObject lRecord = new BasicDBObject();
                lRecord.put("correlationId", lCorrelationId);
                lRecord.put("destination", lDest);
                lRecord.put("connectionId", aInfo.getConsumerId().getConnectionId());
                String lConsumerId = aInfo.getConsumerId().toString();
                lRecord.put("consumerId", lConsumerId);
                // saving record
                lCollection.update(new BasicDBObject().append("correlationId", lCorrelationId), lRecord, true,
                        false);
            }
        }
    }
    return super.addConsumer(aContext, aInfo);
}

From source file:org.keycloak.connections.mongo.updater.impl.updates.Update1_8_0.java

License:Apache License

@Override
public void update(KeycloakSession session) {
    BasicDBList orArgs = new BasicDBList();
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD));
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY));

    BasicDBObject elemMatch = new BasicDBObject("$or", orArgs);
    elemMatch.put("algorithm", new BasicDBObject("$exists", false));

    BasicDBObject query = new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch));

    BasicDBObject update = new BasicDBObject("$set",
            new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID));

    DBCollection users = db.getCollection("users");

    // Not sure how to do in single query
    int countModified = 1;
    while (countModified > 0) {
        WriteResult wr = users.update(query, update, false, true);
        countModified = wr.getN();/*w ww  .j a va2 s. co m*/
        log.debugf("%d credentials modified in current iteration during upgrade to 1.8", countModified);
    }
}

From source file:org.keycloak.connections.mongo.updater.impl.updates.Update1_9_2.java

License:Apache License

@Override
public void update(KeycloakSession session) {
    BasicDBList orArgs = new BasicDBList();
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD));
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY));

    BasicDBObject elemMatch = new BasicDBObject("$or", orArgs);
    elemMatch.put("algorithm", HmacOTP.HMAC_SHA1);

    BasicDBObject query = new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch));

    BasicDBObject update = new BasicDBObject("$set",
            new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID));

    DBCollection users = db.getCollection("users");

    // Not sure how to do in single query
    int countModified = 1;
    while (countModified > 0) {
        WriteResult wr = users.update(query, update, false, true);
        countModified = wr.getN();//from  w  w  w  . j  av  a  2 s  . c om
        log.debugf("%d credentials modified in current iteration during upgrade to 1.8", countModified);
    }
}

From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java

License:Open Source License

private void countTarget(StatEvent event) throws StatsEngineException {
    BasicDBObject q = new BasicDBObject();
    q.put(EVENT_CLIENT_ID, event.getClientId());
    q.put(EVENT_TARGET, event.getTarget());
    q.put(EVENT_TARGET_TYPE, event.getTargetType());
    String actionKey = createDotPath(EVENT_ACTION, event.getAction());

    BasicDBObject doc = new BasicDBObject();
    doc.put("$addToSet", createAddToSetOwnersTagsDoc(event));
    BasicDBObject docSet = new BasicDBObject();
    docSet.put(createDotPath(actionKey, TOUCH_DATE), DateUtil.getDateTimeUTC().toDate());
    doc.put("$set", docSet);
    BasicDBObject incDoc = new BasicDBObject();
    incDoc.put(createDotPath(actionKey, FIELD_COUNT), 1); //Global count
    doc.put("$inc", incDoc);
    DBCollection targets = getCounterCollection(event, TimeScope.GLOBAL);
    WriteResult ws = targets.update(q, doc, true, false);
    //log.debug("countTarget result: {}",ws.getLastError());
}

From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java

License:Open Source License

private void countTargetActions(StatEvent event) throws StatsEngineException {
    BasicDBObject q = new BasicDBObject();
    q.put(EVENT_CLIENT_ID, event.getClientId());
    q.put(EVENT_ACTION, event.getAction());
    BasicDBObject doc = new BasicDBObject();
    BasicDBObject docSet = new BasicDBObject();
    docSet.put(TOUCH_DATE, DateUtil.getDateTimeUTC().toDate());
    //docSet.put(TARGET_DATE, event.getDate());
    doc.put("$set", docSet);
    BasicDBObject incDoc = new BasicDBObject();
    incDoc.put(FIELD_TOTAL, 1);/* ww w . ja  va2s . com*/
    incDoc.put(createDotPath(ACTION_TARGET, event.getTargetType(), FIELD_COUNT), 1);
    doc.put("$inc", incDoc);
    DBCollection targetActions = getTargetActionsCollection();
    WriteResult ws = targetActions.update(q, doc, true, false);
    //log.debug("countTarget actions result: {}",ws.getLastError());
}