Example usage for com.mongodb.client FindIterable limit

List of usage examples for com.mongodb.client FindIterable limit

Introduction

In this page you can find the example usage for com.mongodb.client FindIterable limit.

Prototype

FindIterable<TResult> limit(int limit);

Source Link

Document

Sets the limit to apply.

Usage

From source file:MenuIS.java

public static void getIS() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("derivProb", new BasicDBObject("$gt", "0")));

    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results.limit(1)) {

        List<String> conv = (List<String>) doc.get("initialState");

        {//w w  w  .  jav  a  2  s  .c o m

            for (String s : conv)
                ISTextArea.append(s + "\n");

        }
    }
}

From source file:anuncius.singleton.MongoHandler.java

public List<Document> getList(String collectionName, int limit, int sort, Document result, String sortParam) {
    MongoCollection<Document> collection = mainDatabase.getCollection(collectionName);
    if (collection != null) {
        FindIterable<Document> iterable;
        if (result == null) {
            result = new Document();
        }/*from  w w  w . j  a  va2s .  c om*/
        iterable = collection.find(result);
        if (limit > 0) {
            iterable = iterable.limit(limit);
        }
        if (sortParam != null) {
            iterable = iterable.sort(new BasicDBObject(sortParam, sort));
        }
        return iterable.into(new ArrayList<>());
    }
    return new ArrayList<>();
}

From source file:com.bluedragon.mongo.MongoCollectionFind.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData query = getNamedParam(argStruct, "query", null);
    if (query == null)
        throwException(_session, "please specify query");

    int size = getNamedIntParam(argStruct, "size", -1);
    int skip = getNamedIntParam(argStruct, "skip", -1);
    cfData sort = getNamedParam(argStruct, "sort", null);
    cfData fields = getNamedParam(argStruct, "fields", null);

    try {//w  ww.  j a v  a 2s.  c  om
        MongoCollection<Document> col = db.getCollection(collection);

        // Get the initial cursor
        FindIterable<Document> cursor;
        long start = System.currentTimeMillis();
        Document qry = getDocument(query);

        cursor = col.find(qry);

        if (fields != null)
            cursor = cursor.projection(getDocument(fields));

        // Are we sorting?
        if (sort != null)
            cursor = cursor.sort(getDocument(sort));

        // Are we limiting
        if (skip != -1)
            cursor = cursor.skip(skip);

        // How many we bringing back
        if (size != -1)
            cursor = cursor.limit(size);

        // Now we can run the query
        cfArrayData results = cfArrayData.createArray(1);

        cursor.forEach(new Block<Document>() {

            @SuppressWarnings("rawtypes")
            @Override
            public void apply(final Document st) {
                try {
                    results.addElement(tagUtils.convertToCfData((Map) st));
                } catch (cfmRunTimeException e) {
                }
            }
        });

        _session.getDebugRecorder().execMongo(col, "find", qry, System.currentTimeMillis() - start);

        return results;
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.eclipsesource.connect.persistence.MongoStorage.java

License:Open Source License

private FindIterable<Document> prepareIterable(Query<?> query, FindIterable<Document> iterable) {
    if (query.getLimit() != -1) {
        iterable.limit(query.getLimit());
    }//from  w  w w.  j  a va 2s.co m
    if (query.getSortField() != null) {
        iterable.sort(
                new Document(query.getSortField(), query.getSortDirection() == SortDirection.ASC ? 1 : -1));
    }
    if (query.getSkip() != Query.UNDEFINED) {
        iterable.skip(query.getSkip());
    }
    return iterable;
}

From source file:com.github.cherimojava.data.mongo.query.QueryInvocationHandler.java

License:Apache License

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    switch (methodName) {
    case "e":
        // this is just a handout for the entity to get knowledge of what to check
        return this.entityProxy.get();
    case "where":/* fallthrough */
    case "and":
        return this.specifier.get();
    case "iterator":
        FindIterable it = coll.find(Filters.and(filters.toArray(new Bson[] {})));
        if (limit != null) {
            it.limit(limit);
        }/*w ww . j  a v  a2  s .c om*/
        if (skip != null) {
            it.skip(skip);
        }
        if (sorts.size() > 0) {
            it.sort(Sorts.orderBy(sorts));
        }
        return it.iterator();
    case "count":
        return coll.count(Filters.and(filters.toArray(new Bson[] {})));
    case "limit":
        limit = (Integer) args[0];
        return queryEnd.get();
    case "skip":
        skip = (Integer) args[0];
        return queryEnd.get();
    case "sort":
        checkState(!sortSet, "Sorting can be specified only once");
        sortSet = true;
        return querySort.get();
    case "desc":/* fallthrough */
    case "asc":
        return addSortInformation("asc".equals(methodName));
    case "by":
        return addSortInformation(args[0] == QuerySort.Sort.ASC);
    }
    throw new IllegalStateException("Unknown method found: " + methodName);
}

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);
    }/*from  www .java 2s  . c  om*/
    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;
}

From source file:com.imaginea.mongodb.controllers.DocumentController.java

License:Apache License

/**
 * Maps GET Request to get all keys of document inside a collection inside a database present in
 * mongo db to a service function that returns the list. Also forms the JSON response for this
 * request and sent it to client. In case of any exception from the service files an error object
 * if formed.//from w  ww  .  j a  v a2 s  .c o  m
 *
 * @param dbName Name of Database
 * @param collectionName Name of Collection
 * @param connectionId Mongo Db Configuration provided by user to connect to.
 * @param request Get the HTTP request context to extract session parameters
 * @return A String of JSON format with all keys in a collection.
 */
@GET
@Path("/keys")
@Produces(MediaType.APPLICATION_JSON)
public String getKeysRequest(@PathParam("dbName") final String dbName,
        @PathParam("collectionName") final String collectionName, @QueryParam("allKeys") final Boolean allKeys,
        @QueryParam("connectionId") final String connectionId, @Context final HttpServletRequest request) {

    String response = new ResponseTemplate().execute(logger, connectionId, request, new ResponseCallback() {
        public Object execute() throws Exception {
            // Perform the operation here only.
            MongoClient mongoInstance = authService.getMongoInstance(connectionId);

            long count = mongoInstance.getDatabase(dbName).getCollection(collectionName).count();
            FindIterable<Document> findIterable = mongoInstance.getDatabase(dbName)
                    .getCollection(collectionName).find();
            if (!allKeys) {
                findIterable.limit(10);
            }
            MongoCursor<Document> cursor = findIterable.iterator();
            Set<String> completeSet = new HashSet<String>();
            if (cursor.hasNext()) {
                while (cursor.hasNext()) {
                    Document doc = cursor.next();
                    getNestedKeys(doc, completeSet, "");
                }
            }
            completeSet.remove("_id");
            JSONObject result = new JSONObject();
            result.put("keys", completeSet);
            result.put("count", count);
            return result;
        }
    });
    return response;
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> List<T> search(String unitName, Class<T> cls, Criteria criteria, List<String> orderBy,
        Integer limit) {//w  w  w.  j  a  v  a 2s.c  o  m
    SerializationDefinition def = SerializationDefinition.get(cls);
    if (def == null)
        throw new RuntimeException("Cannot find SerializationDefinition for " + cls.getSimpleName());

    MongoDatabase db = mongoClient.getDatabase(databaseName);

    FindIterable<Document> query = criteria == null ? db.getCollection(unitName).find()
            : db.getCollection(unitName).find(criteria.convert(new FilterQueryBuilder()));

    if (orderBy != null && !orderBy.isEmpty())
        if (orderBy.size() == 1)
            query = query.sort(orderBy(orderBy.get(0)));
        else {
            List<Bson> ob = new ArrayList<>();
            for (String s : orderBy)
                ob.add(orderBy(s));
            query = query.sort(Sorts.orderBy(ob));
        }

    List<T> result = new ArrayList<>();
    MongoCursor<Document> cursor = query.limit(limit).iterator();
    try {
        while (cursor.hasNext()) {
            T item = (T) def.newInstance();
            def.read(cursor.next(), item);
            result.add(item);
        }
    } finally {
        cursor.close();
    }

    return result;
}

From source file:com.redhat.thermostat.gateway.service.jvms.mongo.JvmInfoMongoStorageHandler.java

License:Open Source License

public String getJvmsTree(MongoCollection<Document> collection, boolean aliveOnly, String excludes,
        String includes, int limit, int offset) {
    FindIterable<Document> documents;

    if (aliveOnly) {
        documents = collection.find(lt(StorageFields.STOP_TIME, 0));
    } else {//from  ww w.j a va 2s .com
        documents = collection.find();
    }

    documents = documents.limit(limit).skip(offset);

    boolean includeSystemId = true;
    if (excludes != null) {
        List<String> excludesList = new ArrayList<>(Arrays.asList(excludes.split(",")));
        if (excludesList.contains(StorageFields.SYSTEM_ID)) {
            excludesList.remove(StorageFields.SYSTEM_ID);
            includeSystemId = false;
        }
        if (excludesList.size() > 0) {
            documents = documents.projection(fields(exclude(excludesList), excludeId()));
        } else {
            documents = documents.projection(excludeId());
        }
    } else if (includes != null) {
        List<String> includesList = new ArrayList<>(Arrays.asList(includes.split(",")));
        if (!includesList.contains(StorageFields.SYSTEM_ID)) {
            includesList.add(StorageFields.SYSTEM_ID);
            includeSystemId = false;
        }
        documents = documents.projection(fields(include(includesList), excludeId()));
    } else {
        documents = documents.projection(excludeId());
    }

    final Map<String, StringBuilder> map = new HashMap<>();

    final boolean finalIncludeSystemId = includeSystemId;
    documents.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {
            String systemId = document.getString(StorageFields.SYSTEM_ID);
            if (!finalIncludeSystemId) {
                document.remove(StorageFields.SYSTEM_ID);
            }

            if (!map.containsKey(systemId)) {
                map.put(systemId, new StringBuilder().append("{\"" + StorageFields.SYSTEM_ID + "\":\""
                        + systemId + "\", \"" + StorageFields.JVMS + "\":["));
            }

            map.get(systemId).append(document.toJson()).append(",");
        }
    });

    StringBuilder responseBuilder = new StringBuilder().append("{ \"" + StorageFields.RESPONSE + "\" : [");
    if (map.size() > 0) {
        for (StringBuilder systemBuilder : map.values()) {
            responseBuilder.append(systemBuilder.deleteCharAt(systemBuilder.length() - 1).toString());
            responseBuilder.append("]},");
        }
        responseBuilder.deleteCharAt(responseBuilder.length() - 1);
    }
    responseBuilder.append("]}");

    return responseBuilder.toString();
}

From source file:io.dirigible.mongodb.jdbc.MongodbStatement.java

License:Apache License

/**
 * Input string: the document specification as defined in https://docs.mongodb.org/manual/reference/command/find/#dbcmd.find
 *//* w  w w .  j a  va2  s  .  c  om*/
@Override
public ResultSet executeQuery(String sql) throws SQLException {
    MongoDatabase db = this.conn.getMongoDb();
    BsonDocument filterDocument = null;
    if (sql == null || sql.length() < 1)//that is a call to find() in terms of mongodb queries
        filterDocument = new BsonDocument();
    else
        filterDocument = BsonDocument.parse(sql);
    /*
     *  TODO: With 3.2 use https://docs.mongodb.org/manual/reference/command/find/#dbcmd.find instead
     *    Document response = this.conn.getMongoDb().runCommand(filterDocument); //MongoDB 3.2 only. Won't work on 3.0
     */
    String collectionName = filterDocument.containsKey("find") ? filterDocument.getString("find").getValue()
            : null;
    if (collectionName == null)
        collectionName = this.conn.getCollectionName();//fallback if any
    if (collectionName == null)
        throw new IllegalArgumentException("Specifying a collection is mandatory for query operations");
    BsonDocument filter = filterDocument.containsKey("filter") ? filterDocument.getDocument("filter") : null;

    FindIterable<Document> searchHits = null;
    if (filter == null)
        searchHits = db.getCollection(collectionName).find();
    else
        searchHits = db.getCollection(collectionName).find(filter);
    if (filterDocument.containsKey("batchSize"))
        searchHits.batchSize(filterDocument.getInt32("batchSize").getValue());
    if (filterDocument.containsKey("limit"))
        searchHits.limit(filterDocument.getInt32("limit").getValue());
    if (filterDocument.containsKey("sort"))
        searchHits.sort(filterDocument.getDocument("sort"));
    return new MongodbResultSet(this, searchHits);
}