Example usage for com.mongodb.client.model Aggregates unwind

List of usage examples for com.mongodb.client.model Aggregates unwind

Introduction

In this page you can find the example usage for com.mongodb.client.model Aggregates unwind.

Prototype

public static Bson unwind(final String fieldName) 

Source Link

Document

Creates a $unwind pipeline stage for the specified field name, which must be prefixed by a '$' sign.

Usage

From source file:co.aurasphere.mongodb.university.classes.m101j.homework31.MainClass.java

License:Open Source License

/**
 * The main method.//  ww w.ja va2s  .co  m
 *
 * @param args
 *            the arguments
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("school");
    MongoCollection<Document> students = db.getCollection("students");

    // Gets all the students.
    MongoCursor<Document> cursor = students.find().iterator();

    try {
        while (cursor.hasNext()) {
            Document student = cursor.next();
            List<Document> scores = (List<Document>) student.get("scores");

            // Finds the lowest homework score.
            Document minScoreObj = null;
            double minScore = Double.MAX_VALUE;

            for (Document scoreDocument : scores) {
                double score = scoreDocument.getDouble("score");
                String type = scoreDocument.getString("type");

                // Swaps the scores.
                if (type.equals("homework") && score < minScore) {
                    minScore = score;
                    minScoreObj = scoreDocument;
                }
            }

            // Removes the lowest score.
            if (minScoreObj != null) {
                scores.remove(minScoreObj);
            }

            // Updates the record.
            students.updateOne(Filters.eq("_id", student.get("_id")),
                    new Document("$set", new Document("scores", scores)));
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = students.aggregate(Arrays.asList(Aggregates.unwind("$scores"),
                Aggregates.group("$_id", Accumulators.avg("average", "$scores.score")),
                Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:mongodb_teste.Jmongo.java

private void jBProfSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProfSearchActionPerformed
    // TODO add your handling code here:
    jshowProfSearch.setText("");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", jSearchName.getText()))),
                    Aggregates.unwind("$materias"),
                    Aggregates.group("$materias.nota", Accumulators.sum("total", 1)),
                    Aggregates.sort(new Document("total", -1))));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        jshowProfSearch.append(it.next().toString() + "\n");
    }/*from ww w.  ja v  a  2  s  .c  o  m*/
    mongoClient.close();
}

From source file:mongodb_teste.MongoDB_teste.java

/**
 * @param args the command line arguments
 *//*from w  w  w.j a v a 2 s. co  m*/
public static void teste(String[] args) throws ParseException {
    // TODO code application logic here
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    /*db.getCollection("Professores").insertOne(
    new Document("nome", "Lana")
        .append("email", "123@ufu.com")
        .append("materias", asList(
                new Document()
                        .append("nome", "EDG")
                        .append("nota", "B"),
                new Document()
                        .append("nome", "BD")
                        .append("nota", "B")))
        .append("telefone", "435341543"));*/
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", "Miguel"))),
                    Aggregates.unwind("$materias"),
                    Aggregates.group("$materias.nota", Accumulators.sum("total", 1)),
                    Aggregates.sort(new Document("total", -1))));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        System.out.println(it.next().get("_id"));
    }
}

From source file:org.apache.rya.mongodb.aggregation.AggregationPipelineQueryNode.java

License:Apache License

/**
 * Add a join with an individual {@link StatementPattern} to the pipeline.
 * @param sp The statement pattern to join with
 * @return true if the join was successfully added to the pipeline.
 */// ww w .  ja  v a  2  s.  com
public boolean joinWith(final StatementPattern sp) {
    Preconditions.checkNotNull(sp);
    // 1. Determine shared variables and new variables
    final StatementVarMapping spMap = new StatementVarMapping(sp, varToOriginalName);
    final NavigableSet<String> sharedVars = new ConcurrentSkipListSet<>(spMap.varNames());
    sharedVars.retainAll(assuredBindingNames);
    // 2. Join on one shared variable
    final String joinKey = sharedVars.pollFirst();
    final String collectionName = collection.getNamespace().getCollectionName();
    Bson join;
    if (joinKey == null) {
        return false;
    } else {
        join = Aggregates.lookup(collectionName, HASHES + "." + joinKey, spMap.hashField(joinKey),
                JOINED_TRIPLE);
    }
    pipeline.add(join);
    // 3. Unwind the joined triples so each document represents a binding
    //   set (solution) from the base branch and a triple that may match.
    pipeline.add(Aggregates.unwind("$" + JOINED_TRIPLE));
    // 4. (Optional) If there are any shared variables that weren't used as
    //   the join key, project all existing fields plus a new field that
    //   tests the equality of those shared variables.
    final BasicDBObject matchOpts = getMatchExpression(sp, JOINED_TRIPLE);
    if (!sharedVars.isEmpty()) {
        final List<Bson> eqTests = new LinkedList<>();
        for (final String varName : sharedVars) {
            final String oldField = valueFieldExpr(varName);
            final String newField = joinFieldExpr(spMap.valueField(varName));
            final Bson eqTest = new Document("$eq", Arrays.asList(oldField, newField));
            eqTests.add(eqTest);
        }
        final Bson eqProjectOpts = Projections.fields(Projections.computed(FIELDS_MATCH, Filters.and(eqTests)),
                Projections.include(JOINED_TRIPLE, VALUES, HASHES, TYPES, LEVEL, TIMESTAMP));
        pipeline.add(Aggregates.project(eqProjectOpts));
        matchOpts.put(FIELDS_MATCH, true);
    }
    // 5. Filter for solutions whose triples match the joined statement
    //  pattern, and, if applicable, whose additional shared variables
    //  match the current solution.
    pipeline.add(Aggregates.match(matchOpts));
    // 6. Project the results to include variables from the new SP (with
    // appropriate renaming) and variables referenced only in the base
    // pipeline (with previous names).
    final Bson finalProjectOpts = new StatementVarMapping(sp, varToOriginalName)
            .getProjectExpression(assuredBindingNames, str -> joinFieldExpr(str));
    assuredBindingNames.addAll(spMap.varNames());
    bindingNames.addAll(spMap.varNames());
    pipeline.add(Aggregates.project(finalProjectOpts));
    return true;
}

From source file:org.apache.rya.mongodb.aggregation.AggregationPipelineQueryNode.java

License:Apache License

/**
 * Add a SPARQL projection or multi-projection operation to the pipeline.
 * The number of documents produced by the pipeline after this operation
 * will be the number of documents entering this stage (the number of
 * intermediate results) multiplied by the number of
 * {@link ProjectionElemList}s supplied here. Empty projections are
 * unsupported; if one or more projections given binds zero variables, then
 * the pipeline will be unchanged and the method will return false.
 * @param projections One or more projections, i.e. mappings from the result
 *  at this stage of the query into a set of variables.
 * @return true if the projection(s) were added to the pipeline.
 *///w  w w. j  av a 2  s  .co  m
public boolean project(final Iterable<ProjectionElemList> projections) {
    if (projections == null || !projections.iterator().hasNext()) {
        return false;
    }
    final List<Bson> projectOpts = new LinkedList<>();
    final Set<String> bindingNamesUnion = new HashSet<>();
    Set<String> bindingNamesIntersection = null;
    for (final ProjectionElemList projection : projections) {
        if (projection.getElements().isEmpty()) {
            // Empty projections are unsupported -- fail when seen
            return false;
        }
        final Document valueDoc = new Document();
        final Document hashDoc = new Document();
        final Document typeDoc = new Document();
        final Set<String> projectionBindingNames = new HashSet<>();
        for (final ProjectionElem elem : projection.getElements()) {
            String to = elem.getTargetName();
            // If the 'to' name is invalid, replace it internally
            if (!isValidFieldName(to)) {
                to = replace(to);
            }
            String from = elem.getSourceName();
            // If the 'from' name is invalid, use the internal substitute
            if (varToOriginalName.containsValue(from)) {
                from = varToOriginalName.inverse().get(from);
            }
            projectionBindingNames.add(to);
            if (to.equals(from)) {
                valueDoc.append(to, 1);
                hashDoc.append(to, 1);
                typeDoc.append(to, 1);
            } else {
                valueDoc.append(to, valueFieldExpr(from));
                hashDoc.append(to, hashFieldExpr(from));
                typeDoc.append(to, typeFieldExpr(from));
            }
        }
        bindingNamesUnion.addAll(projectionBindingNames);
        if (bindingNamesIntersection == null) {
            bindingNamesIntersection = new HashSet<>(projectionBindingNames);
        } else {
            bindingNamesIntersection.retainAll(projectionBindingNames);
        }
        projectOpts.add(new Document().append(VALUES, valueDoc).append(HASHES, hashDoc).append(TYPES, typeDoc)
                .append(LEVEL, "$" + LEVEL).append(TIMESTAMP, "$" + TIMESTAMP));
    }
    if (projectOpts.size() == 1) {
        pipeline.add(Aggregates.project(projectOpts.get(0)));
    } else {
        final String listKey = "PROJECTIONS";
        final Bson projectIndividual = Projections.fields(
                Projections.computed(VALUES, "$" + listKey + "." + VALUES),
                Projections.computed(HASHES, "$" + listKey + "." + HASHES),
                Projections.computed(TYPES, "$" + listKey + "." + TYPES), Projections.include(LEVEL),
                Projections.include(TIMESTAMP));
        pipeline.add(Aggregates.project(Projections.computed(listKey, projectOpts)));
        pipeline.add(Aggregates.unwind("$" + listKey));
        pipeline.add(Aggregates.project(projectIndividual));
    }
    assuredBindingNames.clear();
    bindingNames.clear();
    assuredBindingNames.addAll(bindingNamesIntersection);
    bindingNames.addAll(bindingNamesUnion);
    return true;
}

From source file:org.opencb.cellbase.lib.impl.GeneMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getTfbs(Query query, QueryOptions queryOptions) {
    Bson bsonQuery = parseQuery(query);//w w w  .  j a v a2s.  c o  m
    Bson match = Aggregates.match(bsonQuery);

    // We parse user's exclude options, ONLY _id can be added if exists
    Bson includeAndExclude;
    Bson exclude = null;
    if (queryOptions != null && queryOptions.containsKey("exclude")) {
        List<String> stringList = queryOptions.getAsStringList("exclude");
        if (stringList.contains("_id")) {
            exclude = Aggregates.project(Projections.exclude("_id"));
        }
    }
    if (exclude != null) {
        includeAndExclude = Aggregates
                .project(Projections.fields(Projections.excludeId(), Projections.include("transcripts.tfbs")));
    } else {
        includeAndExclude = Aggregates.project(Projections.include("transcripts.tfbs"));
    }

    Bson unwind = Aggregates.unwind("$transcripts");
    Bson unwind2 = Aggregates.unwind("$transcripts.tfbs");

    // This project the three fields of Xref to the top of the object
    Document document = new Document("tfName", "$transcripts.tfbs.tfName");
    document.put("pwm", "$transcripts.tfbs.pwm");
    document.put("chromosome", "$transcripts.tfbs.chromosome");
    document.put("start", "$transcripts.tfbs.start");
    document.put("end", "$transcripts.tfbs.end");
    document.put("strand", "$transcripts.tfbs.strand");
    document.put("relativeStart", "$transcripts.tfbs.relativeStart");
    document.put("relativeEnd", "$transcripts.tfbs.relativeEnd");
    document.put("score", "$transcripts.tfbs.score");
    Bson project = Aggregates.project(document);

    return mongoDBCollection.aggregate(Arrays.asList(match, includeAndExclude, unwind, unwind2, project),
            queryOptions);
}

From source file:org.opencb.cellbase.lib.impl.XRefMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult nativeGet(Query query, QueryOptions options) {
    Bson bson = parseQuery(query);//from   w  w  w.j a v  a  2s  .  com
    Bson match = Aggregates.match(bson);

    Bson project = Aggregates.project(Projections.include("transcripts.xrefs"));
    Bson unwind = Aggregates.unwind("$transcripts");
    Bson unwind2 = Aggregates.unwind("$transcripts.xrefs");

    // This project the three fields of Xref to the top of the object
    Document document = new Document("id", "$transcripts.xrefs.id");
    document.put("dbName", "$transcripts.xrefs.dbName");
    document.put("dbDisplayName", "$transcripts.xrefs.dbDisplayName");
    Bson project1 = Aggregates.project(document);

    return mongoDBCollection.aggregate(Arrays.asList(match, project, unwind, unwind2, project1), options);
}

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

License:Apache License

@Override
public QueryResult<StudyAclEntry> getDaemonAcl(List<String> members) throws CatalogDBException {
    long startTime = startQuery();

    Bson match = Aggregates.match(Filters.eq(PRIVATE_ID, "METADATA"));
    Bson unwind = Aggregates.unwind("$" + CatalogCohortDBAdaptor.QueryParams.ACL.key());
    Bson match2 = Aggregates.match(Filters.in(CatalogCohortDBAdaptor.QueryParams.ACL_MEMBER.key(), members));
    Bson project = Aggregates.project(Projections.include(CatalogCohortDBAdaptor.QueryParams.ID.key(),
            CatalogCohortDBAdaptor.QueryParams.ACL.key()));

    QueryResult<Document> aggregate = metaCollection.aggregate(Arrays.asList(match, unwind, match2, project),
            null);/*  www.j  ava 2  s. c  om*/
    StudyAclEntry result = null;
    if (aggregate.getNumResults() == 1) {
        result = parseObject(((Document) aggregate.getResult().get(0).get("acl")), StudyAclEntry.class);
    }
    return endQuery("get daemon Acl", startTime, Arrays.asList(result));
}

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

License:Apache License

@Override
public QueryResult<AuthenticationOrigin> getAuthenticationOrigin(String authId) throws CatalogDBException {
    long startTime = startQuery();

    Bson match = Aggregates.match(Filters.eq(PRIVATE_ID, "METADATA"));
    Bson unwind = Aggregates.unwind("$authenticationOrigins");
    Bson match2 = Aggregates.match(Filters.in("authenticationOrigins.id", authId));
    Bson project = Aggregates.project(Projections.include("authenticationOrigins"));

    QueryResult<Document> aggregate = metaCollection.aggregate(Arrays.asList(match, unwind, match2, project),
            null);//from  w w  w  .j  a v  a 2  s  .c o  m
    AuthenticationOrigin result = null;
    if (aggregate.getNumResults() == 1) {
        result = parseObject(((Document) aggregate.getResult().get(0).get("authenticationOrigins")),
                AuthenticationOrigin.class);
    }
    return endQuery("get authenticationOrigin", startTime, Arrays.asList(result));
}

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

License:Apache License

@Override
public QueryResult<AclEntry> getProjectAcl(long projectId, String userId) throws CatalogDBException {
    long startTime = startQuery();
    /*//w  ww  .jav  a 2 s .c  o  m
    DBObject match1 = new BasicDBObject("$match", new BasicDBObject("projects.id", projectId));
    DBObject project = new BasicDBObject("$project", BasicDBObjectBuilder
        .start("_id", false)
        .append("projects.acl", true)
        .append("projects.id", true).get());
    DBObject unwind1 = new BasicDBObject("$unwind", "$projects");
    DBObject match2 = new BasicDBObject("$match", new BasicDBObject("projects.id", projectId));
    DBObject unwind2 = new BasicDBObject("$unwind", "$projects.acl");
    DBObject match3 = new BasicDBObject("$match", new BasicDBObject("projects.acl.userId", userId));
            
    */
    Bson match1 = Aggregates.match(Filters.eq("projects.id", projectId));
    //        Bson project = Projections.fields(Projections.excludeId(), Projections.include("projects.acl", "projects.id"));
    Bson project = Aggregates.project(
            Projections.fields(Projections.excludeId(), Projections.include("projects.acl", "projects.id")));
    Bson unwind1 = Aggregates.unwind("$projects");
    Bson match2 = Aggregates.match(Filters.eq("projects.id", projectId));
    Bson unwind2 = Aggregates.unwind("$projects.acl");
    Bson match3 = Aggregates.match(Filters.eq("projects.acl.userId", userId));

    List<Bson> operations = new LinkedList<>();
    operations.add(match1);
    operations.add(project);
    operations.add(unwind1);
    operations.add(match2);
    operations.add(unwind2);
    operations.add(match3);

    QueryResult aggregate = userCollection.aggregate(operations, null);
    List<AclEntry> acls = new LinkedList<>();
    if (aggregate.getNumResults() != 0) {
        //            DBObject aclObject = (DBObject) ((DBObject) ((DBObject) aggregate.getResult().get(0)).get("projects")).get("acl");
        Document aclObject = (Document) ((Document) ((Document) aggregate.getResult().get(0)).get("projects"))
                .get("acl");
        AclEntry acl = parseObject(aclObject, AclEntry.class);
        acls.add(acl);
    }
    return endQuery("get project ACL", startTime, acls);
}