Example usage for com.mongodb.client MongoCollection aggregate

List of usage examples for com.mongodb.client MongoCollection aggregate

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection aggregate.

Prototype

AggregateIterable<TDocument> aggregate(List<? extends Bson> pipeline);

Source Link

Document

Aggregates documents according to the specified aggregation pipeline.

Usage

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereHugeIn() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {\"bsid\": {$in: [" + DemoData.joinByComma(DemoUtils.getBsIds())
                            + "]}}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();//from  www  . ja  v a2 s  . co m

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereManyIn() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {\"prg\": {$in: [" + DemoData.SCALAR_IN_1_AS_STRING
                            + "]}, \"prr\": {$in: [" + DemoData.SCALAR_IN_2_AS_STRING + "]}}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();/*from w  ww  .j a va 2 s .com*/

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereManyHugeIn() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {\"prr\": {$in: [" + DemoData.SCALAR_IN_1_AS_STRING
                            + "]}, \"bsid\": {$in: [" + DemoData.joinByComma(DemoUtils.getBsIds()) + "]}}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();/*from   ww  w. ja v  a2s .  c om*/

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereRange() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {\"vlc\": {$gt: " + DemoData.RANGE_LEFT + ", $lt: "
                            + DemoData.RANGE_RIGHT + "}}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();/*from ww w  .ja  v a2 s .  co m*/

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereManyRange() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {" + "$and: [" + "{\"vlc\": {$gt: " + DemoData.RANGE_LEFT
                            + ", $lt: " + DemoData.RANGE_RIGHT + "}}, {\"vch\": {$gt: " + DemoData.RANGE_LEFT
                            + ", $lt: " + DemoData.RANGE_RIGHT + "}}" + "]}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();//from   w  ww.  ja va2 s.  c  om

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereStringLike() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(Document.parse("{$match: {tr: /" + DemoData.STRING_LIKE + "/}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();// www  .ja v  a2  s.  c  o  m

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereString() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(Document.parse("{$match: {tr: \"" + DemoData.STRING_LIKE + "\"}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();//  w  w w.  j av a2 s  .c  o m

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereSimpleRangeInStringLike() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {$and: [{prr: 1}, {prg: {$in: [" + DemoData.SCALAR_IN_1_AS_STRING
                            + "]}}, {vlc: {$gt: " + DemoData.RANGE_LEFT + ", $lt: " + DemoData.RANGE_RIGHT
                            + "}}, {tr: /" + DemoData.STRING_LIKE + "/}]}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();/*  w w w  . jav  a2  s.c  om*/

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.helion3.prism.storage.mongodb.MongoRecords.java

License:MIT License

@Override
public CompletableFuture<List<Result>> query(QuerySession session, boolean translate) throws Exception {
    Query query = session.getQuery();
    checkNotNull(query);/*w  w w.j  a va  2s  .c  o  m*/

    // Prepare results
    List<Result> results = new ArrayList<Result>();
    CompletableFuture<List<Result>> future = new CompletableFuture<List<Result>>();

    // Get collection
    MongoCollection<Document> collection = MongoStorageAdapter
            .getCollection(MongoStorageAdapter.collectionEventRecordsName);

    // Append all conditions
    Document matcher = new Document("$match", buildConditions(query.getConditions()));

    // Session configs
    int sortDir = 1; // @todo needs implementation
    boolean shouldGroup = query.isAggregate();

    // Sorting
    Document sortFields = new Document();
    sortFields.put(DataQueries.Created.toString(), sortDir);
    sortFields.put(DataQueries.Y.toString(), 1);
    sortFields.put(DataQueries.X.toString(), 1);
    sortFields.put(DataQueries.Z.toString(), 1);
    Document sorter = new Document("$sort", sortFields);

    // Offset/Limit
    Document limit = new Document("$limit", query.getLimit());

    // Build aggregators
    AggregateIterable<Document> aggregated = null;
    if (shouldGroup) {
        // Grouping fields
        Document groupFields = new Document();
        groupFields.put(DataQueries.EventName.toString(), "$" + DataQueries.EventName);
        groupFields.put(DataQueries.Player.toString(), "$" + DataQueries.Player);
        groupFields.put(DataQueries.Cause.toString(), "$" + DataQueries.Cause);
        groupFields.put(DataQueries.Target.toString(), "$" + DataQueries.Target);
        // Entity
        groupFields.put(DataQueries.Entity.toString(), "$" + DataQueries.Entity.then(DataQueries.EntityType));
        // Day
        groupFields.put("dayOfMonth", new Document("$dayOfMonth", "$" + DataQueries.Created));
        groupFields.put("month", new Document("$month", "$" + DataQueries.Created));
        groupFields.put("year", new Document("$year", "$" + DataQueries.Created));

        Document groupHolder = new Document("_id", groupFields);
        groupHolder.put(DataQueries.Count.toString(), new Document("$sum", 1));

        Document group = new Document("$group", groupHolder);

        // Aggregation pipeline
        List<Document> pipeline = new ArrayList<Document>();
        pipeline.add(matcher);
        pipeline.add(group);
        pipeline.add(sorter);
        pipeline.add(limit);

        aggregated = collection.aggregate(pipeline);
        Prism.getLogger().debug("MongoDB Query: " + pipeline);
    } else {
        // Aggregation pipeline
        List<Document> pipeline = new ArrayList<Document>();
        pipeline.add(matcher);
        pipeline.add(sorter);
        pipeline.add(limit);

        aggregated = collection.aggregate(pipeline);
        Prism.getLogger().debug("MongoDB Query: " + pipeline);
    }

    session.getCommandSource().get()
            .sendMessage(Format.subduedHeading("Query completed, building snapshots..."));

    // Iterate results and build our event record list
    MongoCursor<Document> cursor = aggregated.iterator();
    try {
        List<UUID> uuidsPendingLookup = new ArrayList<UUID>();

        while (cursor.hasNext()) {
            // Mongo document
            Document wrapper = cursor.next();
            Document document = shouldGroup ? (Document) wrapper.get("_id") : wrapper;

            DataContainer data = documentToDataContainer(document);

            if (shouldGroup) {
                data.set(DataQueries.Count, wrapper.get(DataQueries.Count.toString()));
            }

            // Build our result object
            Result result = Result.from(wrapper.getString(DataQueries.EventName.toString()),
                    session.getQuery().isAggregate());

            // Determine the final name of the event source
            if (document.containsKey(DataQueries.Player.toString())) {
                String uuid = document.getString(DataQueries.Player.toString());
                data.set(DataQueries.Cause, uuid);

                if (translate) {
                    uuidsPendingLookup.add(UUID.fromString(uuid));
                }
            } else {
                data.set(DataQueries.Cause, document.getString(DataQueries.Cause.toString()));
            }

            result.data = data;
            results.add(result);
        }

        if (translate && !uuidsPendingLookup.isEmpty()) {
            DataUtil.translateUuidsToNames(results, uuidsPendingLookup).thenAccept(finalResults -> {
                future.complete(finalResults);
            });
        } else {
            future.complete(results);
        }
    } finally {
        cursor.close();
    }

    return future;
}

From source file:com.mycompany.citysearchnosql.Executioner.java

public static void main(final String[] args) {

    // 1. Connect to MongoDB instance running on localhost
    MongoClient mongoClient = new MongoClient();

    // Access database named 'test'
    MongoDatabase database = mongoClient.getDatabase("test");

    // Access collection named 'restaurants'
    MongoCollection<Document> collection = database.getCollection("restaurants");

    // 2. Insert 
    List<Document> documents = asList(
            new Document("name", "Sun Bakery Trattoria").append("stars", 4).append("categories",
                    asList("Pizza", "Pasta", "Italian", "Coffee", "Sandwiches")),
            new Document("name", "Blue Bagels Grill").append("stars", 3).append("categories",
                    asList("Bagels", "Cookies", "Sandwiches")),
            new Document("name", "Hot Bakery Cafe").append("stars", 4).append("categories",
                    asList("Bakery", "Cafe", "Coffee", "Dessert")),
            new Document("name", "XYZ Coffee Bar").append("stars", 5).append("categories",
                    asList("Coffee", "Cafe", "Bakery", "Chocolates")),
            new Document("name", "456 Cookies Shop").append("stars", 4).append("categories",
                    asList("Bakery", "Cookies", "Cake", "Coffee")));

    collection.insertMany(documents);/*from  ww w . j  a va2 s .  co  m*/

    // 3. Query 
    List<Document> results = collection.find().into(new ArrayList<>());

    // 4. Create Index 
    collection.createIndex(Indexes.ascending("name"));
    // 5. Perform Aggregation
    collection.aggregate(asList(match(eq("categories", "Bakery")), group("$stars", sum("count", 1))));

    mongoClient.close();
}