Example usage for com.mongodb.client.model Updates set

List of usage examples for com.mongodb.client.model Updates set

Introduction

In this page you can find the example usage for com.mongodb.client.model Updates set.

Prototype

public static <TItem> Bson set(final String fieldName, @Nullable final TItem value) 

Source Link

Document

Creates an update that sets the value of the field with the given name to the given value.

Usage

From source file:com.exorath.service.hideplayers.service.MongoService.java

License:Apache License

@Override
public Success setVisibilityPlayer(String uuid, VisibilityPlayer player) {
    try {/*from  w w w . jav  a  2  s  .  c o m*/
        visibilityPlayersCollection.updateOne(new Document("_id", uuid),
                Updates.set("state", player.getState().toString()), new UpdateOptions().upsert(true));
        return new Success(true);
    } catch (Exception e) {
        e.printStackTrace();
        return new Success(false, -1, e.getMessage());
    }
}

From source file:documentation.ChangeStreamSamples.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
 *///  w w  w .j a  va 2s .  com
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create("mongodb://localhost:27017,localhost:27018,localhost:27019");
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // Select the MongoDB database.
    MongoDatabase database = mongoClient.getDatabase("testChangeStreams");
    database.drop();
    sleep();

    // Select the collection to query.
    MongoCollection<Document> collection = database.getCollection("documents");

    /*
     * Example 1
     * Create a simple change stream against an existing collection.
     */
    System.out.println("1. Initial document from the Change Stream:");

    // Create the change stream cursor.
    MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor();

    // Insert a test document into the collection.
    collection.insertOne(Document.parse("{username: 'alice123', name: 'Alice'}"));
    ChangeStreamDocument<Document> next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();

    /*
     * Example 2
     * Create a change stream with 'lookup' option enabled.
     * The test document will be returned with a full version of the updated document.
     */
    System.out.println("2. Document from the Change Stream, with lookup enabled:");

    // Create the change stream cursor.
    cursor = collection.watch().fullDocument(FullDocument.UPDATE_LOOKUP).cursor();

    // Update the test document.
    collection.updateOne(Document.parse("{username: 'alice123'}"),
            Document.parse("{$set : { email: 'alice@example.com'}}"));

    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();

    /*
     * Example 3
     * Create a change stream with 'lookup' option using a $match and ($redact or $project) stage.
     */
    System.out.println(
            "3. Document from the Change Stream, with lookup enabled, matching `update` operations only: ");

    // Insert some dummy data.
    collection.insertMany(asList(Document.parse("{updateMe: 1}"), Document.parse("{replaceMe: 1}")));

    // Create $match pipeline stage.
    List<Bson> pipeline = singletonList(
            Aggregates.match(Filters.or(Document.parse("{'fullDocument.username': 'alice123'}"),
                    Filters.in("operationType", asList("update", "replace", "delete")))));

    // Create the change stream cursor with $match.
    cursor = collection.watch(pipeline).fullDocument(FullDocument.UPDATE_LOOKUP).cursor();

    // Forward to the end of the change stream
    next = cursor.tryNext();

    // Update the test document.
    collection.updateOne(Filters.eq("updateMe", 1), Updates.set("updated", true));
    next = cursor.next();
    System.out.println(format("Update operationType: %s %n %s", next.getUpdateDescription(), next));

    // Replace the test document.
    collection.replaceOne(Filters.eq("replaceMe", 1), Document.parse("{replaced: true}"));
    next = cursor.next();
    System.out.println(format("Replace operationType: %s", next));

    // Delete the test document.
    collection.deleteOne(Filters.eq("username", "alice123"));
    next = cursor.next();
    System.out.println(format("Delete operationType: %s", next));
    cursor.close();
    sleep();

    /**
     * Example 4
     * Resume a change stream using a resume token.
     */
    System.out.println("4. Document from the Change Stream including a resume token:");

    // Get the resume token from the last document we saw in the previous change stream cursor.
    BsonDocument resumeToken = cursor.getResumeToken();
    System.out.println(resumeToken);

    // Pass the resume token to the resume after function to continue the change stream cursor.
    cursor = collection.watch().resumeAfter(resumeToken).cursor();

    // Insert a test document.
    collection.insertOne(Document.parse("{test: 'd'}"));

    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
}

From source file:eu.project.ttc.models.occstore.MongoDBOccurrenceStore.java

License:Apache License

@Override
public void flush() {

    // bulk write occurrences
    final List<org.bson.Document> occDocuments = Lists.newArrayListWithCapacity(occurrencesBuffer.size());
    for (TermOccurrence o : this.occurrencesBuffer) {

        occDocuments.add(new org.bson.Document().append(TERM_ID, o.getTerm().getId())
                .append(DOC_ID, o.getSourceDocument().getId()).append(BEGIN, o.getBegin())
                .append(END, o.getEnd()).append(COVERED_TEXT, o.getCoveredText()));
    }/* www  .j av a 2s  . c  o  m*/
    if (!occurrencesBuffer.isEmpty())
        executor.execute(new Runnable() {
            public void run() {
                occurrenceCollection.insertMany(occDocuments);
            }
        });

    // bulk write documents
    final List<WriteModel<org.bson.Document>> documentUrlsOps = Lists
            .newArrayListWithCapacity(documentsUrls.size());
    for (Map.Entry<Integer, String> e : this.documentsUrls.entrySet()) {
        UpdateOneModel<org.bson.Document> w = new UpdateOneModel<org.bson.Document>(Filters.eq(_ID, e.getKey()),
                Updates.set(DOC_URL, e.getValue()), new UpdateOptions().upsert(true));
        documentUrlsOps.add(w);
    }

    if (!documentUrlsOps.isEmpty())
        executor.execute(new Runnable() {
            public void run() {
                documentUrlCollection.bulkWrite(documentUrlsOps, new BulkWriteOptions().ordered(false));
            }
        });

    // bulk write terms
    final List<WriteModel<org.bson.Document>> termsOps = Lists.newArrayList();
    for (Term t : termsBuffer.keySet()) {
        UpdateOneModel<org.bson.Document> w = new UpdateOneModel<org.bson.Document>(Filters.eq(_ID, t.getId()),
                Updates.inc(FREQUENCY, termsBuffer.get(t).intValue()), new UpdateOptions().upsert(true));
        termsOps.add(w);
    }
    if (!termsOps.isEmpty())
        executor.execute(new Runnable() {
            public void run() {
                termCollection.bulkWrite(termsOps, new BulkWriteOptions().ordered(false));
            }
        });

    resetBuffers();

}

From source file:org.apache.drill.exec.store.mongo.config.MongoPersistentStore.java

License:Apache License

@Override
public boolean putIfAbsent(String key, V value) {
    try {/*from  w  w  w . j av a 2  s. co m*/
        Bson query = Filters.eq(DrillMongoConstants.ID, key);
        Bson update = Updates.set(pKey, bytes(value));
        UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true));
        return updateResult.getModifiedCount() == 1;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new DrillRuntimeException(e.getMessage(), e);
    }
}

From source file:org.nuxeo.directory.mongodb.MongoDBSession.java

License:Apache License

@Override
public void updateEntry(DocumentModel docModel) throws DirectoryException {
    checkPermission(SecurityConstants.WRITE);
    Map<String, Object> fieldMap = new HashMap<>();
    List<String> referenceFieldList = new LinkedList<>();

    for (String fieldName : schemaFieldMap.keySet()) {
        Property prop = docModel.getPropertyObject(schemaName, fieldName);
        if (fieldName.equals(getPasswordField()) && StringUtils.isEmpty((String) prop.getValue())) {
            continue;
        }/* w  ww  .j a v  a 2  s .  c  o m*/
        if (prop != null && prop.isDirty()) {
            Serializable value = prop.getValue();
            if (fieldName.equals(getPasswordField())) {
                value = PasswordHelper.hashPassword((String) value, passwordHashAlgorithm);
            }
            fieldMap.put(prop.getName(), value);
        }
        if (getDirectory().isReference(fieldName)) {
            referenceFieldList.add(fieldName);
        }
    }

    String id = docModel.getId();
    Document bson = MongoDBSerializationHelper.fieldMapToBson(getIdField(), id);

    List<Bson> updates = fieldMap.entrySet().stream().map(e -> Updates.set(e.getKey(), e.getValue()))
            .collect(Collectors.toList());

    try {
        UpdateResult result = getCollection().updateOne(bson, Updates.combine(updates));
        // Throw an error if no document matched the update
        if (!result.wasAcknowledged()) {
            throw new DirectoryException(
                    "Error while updating the entry, the request has not been acknowledged by the server");
        }
        if (result.getMatchedCount() == 0) {
            throw new DirectoryException(
                    String.format("Error while updating the entry, no document was found with the id %s", id));
        }
    } catch (MongoWriteException e) {
        throw new DirectoryException(e);
    }

    // update reference fields
    for (String referenceFieldName : referenceFieldList) {
        List<Reference> references = directory.getReferences(referenceFieldName);
        if (references.size() > 1) {
            // not supported
            log.warn("Directory " + getDirectory().getName() + " cannot update field " + referenceFieldName
                    + " for entry " + docModel.getId()
                    + ": this field is associated with more than one reference");
        } else {
            Reference reference = references.get(0);
            @SuppressWarnings("unchecked")
            List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName);
            if (reference instanceof MongoDBReference) {
                MongoDBReference mongoReference = (MongoDBReference) reference;
                mongoReference.setTargetIdsForSource(docModel.getId(), targetIds, this);
            } else {
                reference.setTargetIdsForSource(docModel.getId(), targetIds);
            }
        }
    }
    getDirectory().invalidateCaches();

}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoProjectDBAdaptor.java

License:Apache License

@Override
public QueryResult renameProjectAlias(long projectId, String newProjectAlias) throws CatalogDBException {
    long startTime = startQuery();
    //        String projectOwner = getProjectOwner(projectId);
    ///*from w w w .  ja  v  a  2 s .c o m*/
    //        int collisionProjectId = getProjectId(projectOwner, newProjectAlias);
    //        if (collisionProjectId != -1) {
    //            throw new CatalogManagerException("Couldn't rename project alias, alias already used in the same user");
    //        }

    QueryResult<Project> projectResult = getProject(projectId, null); // if projectId doesn't exist, an exception is raised
    Project project = projectResult.getResult().get(0);

    //String oldAlias = project.getAlias();
    project.setAlias(newProjectAlias);

    /*
    DBObject query = BasicDBObjectBuilder
        .start("projects.id", projectId)
        .append("projects.alias", new BasicDBObject("$ne", newProjectAlias))    // check that any other project in the user has
        // the new name
        .get();
    DBObject update = new BasicDBObject("$set",
        new BasicDBObject("projects.$.alias", newProjectAlias));
    */
    Bson query = Filters.and(Filters.eq("projects.id", projectId),
            Filters.ne("projects.alias", newProjectAlias));
    Bson update = Updates.set("projects.$.alias", newProjectAlias);

    QueryResult<UpdateResult> result = userCollection.update(query, update, null);
    if (result.getResult().get(0).getModifiedCount() == 0) { //Check if the the study has been inserted
        throw new CatalogDBException("Project {alias:\"" + newProjectAlias + "\"} already exists");
    }
    return endQuery("rename project alias", startTime, result);
}

From source file:org.opencb.opencga.catalog.db.mongodb.ProjectMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult renameAlias(long projectId, String newProjectAlias) throws CatalogDBException {
    long startTime = startQuery();
    //        String projectOwner = getProjectOwner(projectId);
    ///*from   w w w  .  j  a  v a 2  s  .co m*/
    //        int collisionProjectId = getProjectId(projectOwner, newProjectAlias);
    //        if (collisionProjectId != -1) {
    //            throw new CatalogManagerException("Couldn't rename project alias, alias already used in the same user");
    //        }

    QueryResult<Project> projectResult = get(projectId, null); // if projectId doesn't exist, an exception is raised
    Project project = projectResult.getResult().get(0);

    //String oldAlias = project.getAlias();
    project.setAlias(newProjectAlias);

    /*
    DBObject query = BasicDBObjectBuilder
        .start("projects.id", projectId)
        .append("projects.alias", new BasicDBObject("$ne", newProjectAlias))    // check that any other project in the user has
        // the new name
        .get();
    DBObject update = new BasicDBObject("$set",
        new BasicDBObject("projects.$.alias", newProjectAlias));
    */
    Bson query = Filters.and(Filters.eq("projects.id", projectId),
            Filters.ne("projects.alias", newProjectAlias));
    Bson update = Updates.set("projects.$.alias", newProjectAlias);

    QueryResult<UpdateResult> result = userCollection.update(query, update, null);
    if (result.getResult().get(0).getModifiedCount() == 0) { //Check if the the study has been inserted
        throw new CatalogDBException("Project {alias:\"" + newProjectAlias + "\"} already exists");
    }
    return endQuery("rename project alias", startTime, result);
}

From source file:org.opencb.opencga.catalog.db.mongodb.SampleMongoDBAdaptor.java

License:Apache License

@Override
@Deprecated/*  ww  w.  j a  v  a2  s .com*/
public QueryResult<AnnotationSet> annotate(long sampleId, AnnotationSet annotationSet, boolean overwrite)
        throws CatalogDBException {
    long startTime = startQuery();

    /*QueryResult<Long> count = sampleCollection.count(
        new BasicDBObject("annotationSets.id", annotationSet.getId()).append(PRIVATE_ID, sampleId));*/
    QueryResult<Long> count = sampleCollection
            .count(new Document("annotationSets.name", annotationSet.getName()).append(PRIVATE_ID, sampleId));
    if (overwrite) {
        if (count.getResult().get(0) == 0) {
            throw CatalogDBException.idNotFound("AnnotationSet", annotationSet.getName());
        }
    } else {
        if (count.getResult().get(0) > 0) {
            throw CatalogDBException.alreadyExists("AnnotationSet", "name", annotationSet.getName());
        }
    }

    /*DBObject object = getDbObject(annotationSet, "AnnotationSet");
            
    DBObject query = new BasicDBObject(PRIVATE_ID, sampleId);*/
    Document object = getMongoDBDocument(annotationSet, "AnnotationSet");

    Bson query = new Document(PRIVATE_ID, sampleId);
    if (overwrite) {
        ((Document) query).put("annotationSets.name", annotationSet.getName());
    } else {
        ((Document) query).put("annotationSets.name", new Document("$ne", annotationSet.getName()));
    }

    /*
    DBObject update;
    if (overwrite) {
    update = new BasicDBObject("$set", new BasicDBObject("annotationSets.$", object));
    } else {
    update = new BasicDBObject("$push", new BasicDBObject("annotationSets", object));
    }
    */

    Bson update;
    if (overwrite) {
        update = Updates.set("annotationSets.$", object);
    } else {
        update = Updates.push("annotationSets", object);
    }

    QueryResult<UpdateResult> queryResult = sampleCollection.update(query, update, null);

    if (queryResult.first().getModifiedCount() != 1) {
        throw CatalogDBException.alreadyExists("AnnotationSet", "name", annotationSet.getName());
    }

    return endQuery("", startTime, Collections.singletonList(annotationSet));
}

From source file:org.opencb.opencga.catalog.db.mongodb.UserMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult logout(String userId, String sessionId) throws CatalogDBException {
    long startTime = startQuery();

    String userIdBySessionId = getUserIdBySessionId(sessionId);
    if (userIdBySessionId.isEmpty()) {
        return endQuery("logout", startTime, null, "", "Session not found");
    }//from  www .  ja v a 2  s  . c  o  m
    if (userIdBySessionId.equals(userId)) {
        Bson query = new Document(QueryParams.SESSION_ID.key(), sessionId);
        Bson updates = Updates.set("sessions.$.logout", TimeUtils.getTime());
        userCollection.update(query, updates, null);
    } else {
        throw new CatalogDBException("UserId mismatches with the sessionId");
    }

    return endQuery("Logout", startTime);
}

From source file:org.opencb.opencga.catalog.db.mongodb.UserMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult changePassword(String userId, String oldPassword, String newPassword)
        throws CatalogDBException {
    long startTime = startQuery();

    //        BasicDBObject query = new BasicDBObject("id", userId);
    //        query.put("password", oldPassword);
    Query query = new Query(QueryParams.ID.key(), userId);
    query.append(QueryParams.PASSWORD.key(), oldPassword);
    Bson bson = parseQuery(query);//from w ww  .  j ava  2s.  c  o  m

    //        BasicDBObject fields = new BasicDBObject("password", newPassword);
    //        BasicDBObject action = new BasicDBObject("$set", fields);
    //        Bson set = Updates.set("password", new Document("password", newPassword));
    Bson set = Updates.set("password", newPassword);

    //        QueryResult<WriteResult> update = userCollection.update(bson, set, null);
    QueryResult<UpdateResult> update = userCollection.update(bson, set, null);
    if (update.getResult().get(0).getModifiedCount() == 0) { //0 query matches.
        throw new CatalogDBException("Bad user or password");
    }
    return endQuery("Change Password", startTime, update);
}