Example usage for com.mongodb.client MongoCursor next

List of usage examples for com.mongodb.client MongoCursor next

Introduction

In this page you can find the example usage for com.mongodb.client MongoCursor next.

Prototype

@Override
    TResult next();

Source Link

Usage

From source file:com.erudika.para.persistence.MongoDBDAO.java

License:Apache License

@Override
public <P extends ParaObject> List<P> readPage(String appid, Pager pager) {
    LinkedList<P> results = new LinkedList<P>();
    if (StringUtils.isBlank(appid)) {
        return results;
    }/*from  w w w. j  av a2 s.  co m*/
    if (pager == null) {
        pager = new Pager();
    }
    try {
        String lastKey = pager.getLastKey();
        MongoCursor<Document> cursor;
        Bson filter = Filters.gt(_OBJECT_ID, lastKey);
        if (lastKey == null) {
            cursor = getTable(appid).find().batchSize(pager.getLimit()).limit(pager.getLimit()).iterator();
        } else {
            cursor = getTable(appid).find(filter).batchSize(pager.getLimit()).limit(pager.getLimit())
                    .iterator();
        }
        while (cursor.hasNext()) {
            Map<String, Object> row = documentToMap(cursor.next());
            P obj = fromRow(row);
            if (obj != null) {
                results.add(obj);
                pager.setLastKey((String) row.get(_OBJECT_ID));
            }
        }
        if (!results.isEmpty()) {
            pager.setCount(pager.getCount() + results.size());
        }
    } catch (Exception e) {
        logger.error(null, e);
    }
    logger.debug("readPage() page: {}, results:", pager.getPage(), results.size());
    return results;
}

From source file:com.facebook.presto.mongodb.MongoSession.java

License:Apache License

private Set<String> getTableMetadataNames(String schemaName) throws TableNotFoundException {
    MongoDatabase db = client.getDatabase(schemaName);
    MongoCursor<Document> cursor = db.getCollection(schemaCollection).find()
            .projection(new Document(TABLE_NAME_KEY, true)).iterator();

    HashSet<String> names = new HashSet<>();
    while (cursor.hasNext()) {
        names.add((cursor.next()).getString(TABLE_NAME_KEY));
    }/*from  w  w  w . j  a  v a  2  s . c  o  m*/

    return names;
}

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

License:Apache License

private static void groupBy(Map<Integer, Map<Integer, Integer>> g, MongoCursor<Document> cursor)
        throws SQLException {
    while (cursor.hasNext()) {
        Document document = cursor.next();
        Document id = (Document) document.get("_id");
        Integer prg = id.getInteger("prg");
        Integer prr = id.getInteger("prr");
        Integer grc = document.getInteger("count");

        Map<Integer, Integer> r = g.get(prg);
        if (r == null) {
            r = new HashMap<>();
            g.put(prg, r);//from ww w . j  a  v a  2  s  .  c  o  m
        }

        Integer c = r.get(prr);
        if (c == null)
            c = 0;
        r.put(prr, c + grc);
    }
}

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

License:Apache License

@Override
public Object selectLimit() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection.find(Document.parse("{\"prg\": {$in: ["
            + DemoData.SCALAR_IN_1_AS_STRING + "]}, \"prr\": {$in: [" + DemoData.SCALAR_IN_2_AS_STRING + "]}}"))
            .limit(25).iterator();/*from   w  w  w .j  a v  a2  s  . c  o  m*/

    List<Object> r = new ArrayList<>();
    while (cursor.hasNext()) {
        r.add(cursor.next());
    }

    cursor.close();
    return r.size();
}

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

License:Apache License

@Override
public Object selectOrderByLimit() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .find(Document.parse("{\"prg\": {$in: [" + DemoData.SCALAR_IN_1_AS_STRING + "]}, \"prr\": {$in: ["
                    + DemoData.SCALAR_IN_2_AS_STRING + "]}}"))
            .sort(Document.parse("{prr: 1}")).limit(25).iterator();

    List<Object> r = new ArrayList<>();
    while (cursor.hasNext()) {
        r.add(cursor.next());
    }// w  ww . ja  v  a2s.co  m

    cursor.close();
    return r.size();
}

From source file:com.glaf.core.config.mongodb.MongodbConfig.java

License:Apache License

public Object get(Object key) {
    BasicDBObject filter = new BasicDBObject();
    filter.put("key", key);
    MongoCursor<Document> cur = dbCollection.find(filter).iterator();
    long now = System.currentTimeMillis();
    Object value = null;/*from   w w  w .ja v  a2s  .co  m*/
    try {
        while (cur.hasNext()) {
            Document doc = cur.next();
            value = doc.get(key.toString());
            long saveTime = (Long) doc.get("time");
            if ((now - saveTime) > expireMinutes * 60000) {
                /**
                 * ???
                 */
                dbCollection.deleteOne(doc);
            }
        }
    } finally {
        cur.close();
    }
    return value;
}

From source file:com.glaf.core.resource.mongodb.MongodbResource.java

License:Apache License

public Object getObject(Object key) {
    BasicDBObject filter = new BasicDBObject();
    filter.put("key", key);
    MongoCursor<Document> cur = dbCollection.find(filter).iterator();
    long now = System.currentTimeMillis();
    Object value = null;//from  ww  w  . j a  v  a 2 s .  co  m
    try {
        while (cur.hasNext()) {
            Document doc = cur.next();
            value = doc.get(key.toString());
            long saveTime = (Long) doc.get("time");
            if ((now - saveTime) > expireMinutes * 60000) {
                /**
                 * ???
                 */
                dbCollection.deleteOne(filter);
            }
        }
    } finally {
        cur.close();
    }
    return value;
}

From source file:com.glaf.j2cache.mongodb.MongodbCache.java

License:Apache License

public Object get(Object key) throws CacheException {
    BasicDBObject filter = new BasicDBObject();
    filter.put("key", key);
    MongoCursor<Document> cur = dbCollection.find(filter).iterator();
    long now = System.currentTimeMillis();
    Object value = null;//from w w  w. j  ava 2 s.  com
    try {
        while (cur.hasNext()) {
            Document doc = cur.next();
            value = doc.get(key.toString());
            long saveTime = (Long) doc.get("time");
            if ((now - saveTime) > expireMinutes * 60000) {
                /**
                 * ?
                 */
                dbCollection.deleteOne(filter);
            }
        }
    } finally {
        cur.close();
    }
    return value;
}

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);/* www .ja  v  a2 s  .  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.hurence.logisland.service.mongodb.MongoDBControllerService.java

License:Apache License

@Override
public List<Document> findMany(Document query, Document sort, int limit) {
    FindIterable<Document> fi = this.col.find(query);
    if (limit > 0) {
        fi = fi.limit(limit);//w w w.  j a  v a 2  s . c o m
    }
    if (sort != null) {
        fi = fi.sort(sort);
    }
    MongoCursor<Document> cursor = fi.iterator();
    List<Document> retVal = new ArrayList<>();
    while (cursor.hasNext()) {
        retVal.add(cursor.next());
    }
    cursor.close();

    return retVal;
}