Example usage for com.mongodb.client MongoCollection find

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

Introduction

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

Prototype

FindIterable<TDocument> find();

Source Link

Document

Finds all documents in the collection.

Usage

From source file:org.apache.eagle.alert.metadata.impl.MongoMetadataDaoImpl.java

License:Apache License

private <T> List<T> list(MongoCollection<Document> collection, Class<T> clz) {
    List<T> result = new LinkedList<T>();
    collection.find().map(new Function<Document, T>() {
        @Override/* ww w  .j a va  2  s. c  o m*/
        public T apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, clz);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).into(result);
    return result;
}

From source file:org.apache.metamodel.mongodb.mongo3.MongoDbDataContext.java

License:Apache License

/**
 * Performs an analysis of an available collection in a Mongo {@link DB}
 * instance and tries to detect the table structure based on the first 1000
 * documents in the collection./*from www  .j av a 2  s. co m*/
 *
 * @param mongoDb
 *            the mongo DB
 * @param collectionName
 *            the name of the collection
 * @return a table definition for mongo db.
 */
public static SimpleTableDef detectTable(MongoDatabase mongoDb, String collectionName) {

    final MongoCollection<Document> collection = mongoDb.getCollection(collectionName);
    final FindIterable<Document> iterable = collection.find().limit(1000);

    final SortedMap<String, Set<Class<?>>> columnsAndTypes = new TreeMap<String, Set<Class<?>>>();
    for (Document document : iterable) {
        Set<String> keysInObject = document.keySet();
        for (String key : keysInObject) {
            Set<Class<?>> types = columnsAndTypes.get(key);
            if (types == null) {
                types = new HashSet<Class<?>>();
                columnsAndTypes.put(key, types);
            }
            Object value = document.get(key);
            if (value != null) {
                types.add(value.getClass());
            }
        }
    }

    final String[] columnNames = new String[columnsAndTypes.size()];
    final ColumnType[] columnTypes = new ColumnType[columnsAndTypes.size()];

    int i = 0;
    for (Entry<String, Set<Class<?>>> columnAndTypes : columnsAndTypes.entrySet()) {
        final String columnName = columnAndTypes.getKey();
        final Set<Class<?>> columnTypeSet = columnAndTypes.getValue();
        final Class<?> columnType;
        if (columnTypeSet.size() == 1) {
            columnType = columnTypeSet.iterator().next();
        } else {
            columnType = Object.class;
        }
        columnNames[i] = columnName;
        if (columnType == ObjectId.class) {
            columnTypes[i] = ColumnType.ROWID;
        } else {
            columnTypes[i] = ColumnTypeImpl.convertColumnType(columnType);
        }
        i++;
    }

    return new SimpleTableDef(collectionName, columnNames, columnTypes);
}

From source file:org.axonframework.mongo.eventsourcing.eventstore.AbstractMongoEventStorageStrategy.java

License:Apache License

@Override
public List<? extends TrackedEventData<?>> findTrackedEvents(MongoCollection<Document> eventCollection,
        TrackingToken lastToken, int batchSize) {
    FindIterable<Document> cursor;
    if (lastToken == null) {
        cursor = eventCollection.find();
    } else {//from  w w w  .  j av a 2s.  c  o m
        Assert.isTrue(lastToken instanceof MongoTrackingToken,
                () -> String.format("Token %s is of the wrong type", lastToken));
        MongoTrackingToken trackingToken = (MongoTrackingToken) lastToken;
        cursor = eventCollection.find(and(
                gte(eventConfiguration.timestampProperty(),
                        trackingToken.getTimestamp().minus(lookBackTime).toString()),
                nin(eventConfiguration.eventIdentifierProperty(), trackingToken.getKnownEventIds())));
    }
    cursor = cursor.sort(new BasicDBObject(eventConfiguration().timestampProperty(), ORDER_ASC)
            .append(eventConfiguration().sequenceNumberProperty(), ORDER_ASC));
    cursor = cursor.limit(batchSize);
    AtomicReference<MongoTrackingToken> previousToken = new AtomicReference<>((MongoTrackingToken) lastToken);
    List<TrackedEventData<?>> results = new ArrayList<>();
    for (Document document : cursor) {
        extractEvents(document)
                .filter(ed -> previousToken.get() == null
                        || !previousToken.get().getKnownEventIds().contains(ed.getEventIdentifier()))
                .map(event -> new TrackedMongoEventEntry<>(event,
                        previousToken.updateAndGet(token -> token == null
                                ? MongoTrackingToken.of(event.getTimestamp(), event.getEventIdentifier())
                                : token.advanceTo(event.getTimestamp(), event.getEventIdentifier(),
                                        lookBackTime))))
                .forEach(results::add);
    }
    return results;
}

From source file:org.bananaforscale.cormac.dao.document.DocumentDataServiceImpl.java

License:Apache License

/**
 * Returns all the documents in a collection.
 *
 * @param databaseName the database/*from w  w  w  .j  a  v  a  2s.c  om*/
 * @param collectionName the collection
 * @param query a JSON query param in the style of mongo
 * @param fields fields to return
 * @param skip the amount of documents to skip
 * @param limit the amount of documents to limit the result to
 * @param orderBy order ascending or descending by property
 * @param includeId determines whether to include the Mongo "_id" field
 * @return the documents in a collection
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public List<String> getAll(String databaseName, String collectionName, String query, String fields, String skip,
        String limit, String orderBy, boolean includeId) throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }

        if (!collectionExists(databaseName, collectionName)) {
            throw new NotFoundException("The collection doesn't exist in the datasource");
        }
        Integer intSkip, intLimit;
        try {
            intSkip = Integer.parseInt(skip);
        } catch (NumberFormatException ex) {
            intSkip = 0;
        }
        try {
            intLimit = Integer.parseInt(limit);
        } catch (NumberFormatException ex) {
            intLimit = 0;
        }

        // 1 or -1 to specify an ascending or descending sort respectively.
        Document orderByObject = null;
        if (orderBy != null && !orderBy.isEmpty()) {
            if (orderBy.contains("ascending")) {
                String[] parts = orderBy.split(":");
                orderByObject = new Document(parts[0], 1);
            } else if (orderBy.contains("descending")) {
                String[] parts = orderBy.split(":");
                orderByObject = new Document(parts[0], -1);
            }
        }
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        MongoCollection collection = mongoDatabase.getCollection(collectionName);
        FindIterable iterable = (query == null || query.isEmpty()) ? collection.find()
                : collection.find(Document.parse(query));

        // TODO: Figure out how to do this in new API
        //            if (fields != null && !fields.isEmpty()) {
        //                // expect the form to be field:value,field:value
        //                Document document = new Document();
        //                String[] parts = fields.split(",");
        //                for (String part : parts) {
        //                    String[] tempParts = part.split(":");
        //                    document.append(tempParts[0], tempParts[1]);
        //                }
        //                iterable.projection(document);
        //            }
        iterable.skip(intSkip);
        iterable.limit(intLimit);
        if (orderByObject != null) {
            iterable.sort(orderByObject);
        }
        Iterator<Document> curIter = iterable.iterator();
        List<String> documentList = new ArrayList<>();
        while (curIter.hasNext()) {
            Document current = curIter.next();
            if (!includeId) {
                current.remove("_id");
            }
            documentList.add(JSON.serialize(current));
        }
        return documentList;
    } catch (MongoException ex) {
        logger.error("An error occured while retrieving the document list", ex);
        throw new DatasourceException("An error occured while retrieving the document list");
    }
}

From source file:org.helm.rest.MongoDB.java

public JSONObject List(String table, String cols, BsonDocument where, BsonDocument sortby, int page,
        int countperpage) {
    if (page < 1)
        page = 1;//  ww w.j  a va2s. c  o m
    if (countperpage < 1)
        countperpage = 10;

    long count;
    FindIterable iter;
    MongoCollection coll = db.getCollection(table);
    if (where == null) {
        count = coll.count();
        iter = coll.find();
    } else {
        count = coll.count(where);
        iter = coll.find(where);
    }

    if (sortby != null)
        iter = iter.sort(sortby);

    if (cols != null) {
        String[] ss = cols.split(",");
        Document fields = new Document("_id", false);
        for (int i = 0; i < ss.length; ++i) {
            fields.append(ss[i].trim().toLowerCase(), true);
        }
        iter = iter.projection(fields);
    }

    long mod = count % countperpage;
    long pages = (count - mod) / countperpage + (mod == 0 ? 0 : 1);

    if (page > 1)
        iter = iter.skip((page - 1) * countperpage);
    iter = iter.limit(countperpage);
    MongoCursor cur = iter.iterator();

    JSONObject ret = new JSONObject();
    ret.put("page", page);
    ret.put("pages", pages);
    ret.put("rows", ResultSet2Json(cur));

    cur.close();
    return ret;
}

From source file:org.helm.rest.MongoDB.java

public long[] SelectList(String table, String key, BsonDocument where) {
    key = key.toLowerCase();/*from w  w  w . j a va  2  s .  c  o m*/

    MongoCollection coll = db.getCollection(table);
    Document fields = new Document("_id", false);
    fields.append(key, true);
    MongoCursor cur = (where == null ? coll.find() : coll.find(where)).projection(fields).iterator();
    if (cur == null || !cur.hasNext())
        return null;

    List<Long> list = new ArrayList();
    while (cur.hasNext()) {
        Document d = (Document) cur.next();
        list.add((long) d.get(key));
    }

    long[] ret = new long[list.size()];
    for (int i = 0; i < ret.length; ++i)
        ret[i] = list.get(i);
    return ret;
}

From source file:org.helm.rest.MongoDB.java

public String SelectString(String table, String key, BsonDocument where) {
    key = key.toLowerCase();//from  w ww  .j a  va2  s. c  om

    MongoCollection coll = db.getCollection(table);
    Document fields = new Document("_id", false);
    fields.append(key, true);
    MongoCursor cur = (where == null ? coll.find() : coll.find(where)).limit(1).projection(fields).iterator();
    if (cur == null || !cur.hasNext())
        return null;

    Document d = (Document) cur.next();
    return d.get(key) + "";
}

From source file:org.helm.rest.MongoDB.java

public ArrayList<JSONObject> ReadAsJson(String table, String cols, BsonDocument where) {
    FindIterable iter;//from  ww w.  j  ava  2 s  . c o m
    MongoCollection coll = db.getCollection(table);
    if (where == null) {
        iter = coll.find();
    } else {
        iter = coll.find(where);
    }

    if (cols != null) {
        String[] ss = cols.split(",");
        Document fields = new Document("_id", false);
        for (int i = 0; i < ss.length; ++i) {
            fields.append(ss[i].trim().toLowerCase(), true);
        }
        iter = iter.projection(fields);
    }

    MongoCursor cur = iter.iterator();
    if (cur == null || !cur.hasNext())
        return null;
    return ResultSet2Json(cur);
}

From source file:org.helm.rest.MongoDB.java

public String ReadAsSDF(String table, String molfilekey) {
    MongoCollection coll = db.getCollection(table);
    FindIterable iter = coll.find();

    String lb = System.getProperty("line.separator");
    molfilekey = molfilekey.toLowerCase();
    StringBuilder sb = new StringBuilder();

    if (iter == null) {
        return null;
    } else {//  w  w  w  .  jav  a  2s. c  o  m
        Document fields = new Document("_id", false);
        iter = iter.projection(fields);
    }

    MongoCursor cur = iter.iterator();
    while (cur.hasNext()) {
        Document doc = (Document) cur.next();
        String m = doc.getString(molfilekey);
        if (m != null) {
            // the molfile from toolkit has extra $$$$ line
            // fix bug: https://github.com/PistoiaHELM/HELMWebEditor/issues/94
            int p = m.lastIndexOf("M  END") + 6;
            if (p > 6 && p < m.length() - 1)
                m = m.substring(0, p);
        } else {
            m = lb + "   JSDraw203101711402D" + lb + lb + "  0  0  0  0  0  0              0 V2000" + lb
                    + "M  END";
        }
        sb.append(m);
        sb.append(lb);

        for (String k : doc.keySet()) {
            if (k.equals(molfilekey) || k.equals("_id"))
                continue;

            sb.append("> <");
            sb.append(k);
            sb.append(">");
            sb.append(lb);

            String s = doc.get(k) + "";
            sb.append(s == null ? "" : s);
            sb.append(lb);

            sb.append(lb);
        }
        sb.append("$$$$");
        sb.append(lb);
    }

    return sb.toString();
}

From source file:org.helm.rest.MongoDB.java

long GetMaxID(String table) {
    MongoCollection coll = db.getCollection(table);

    Document fields = new Document("_id", false);
    fields.append("id", true);
    MongoCursor cur = coll.find().projection(fields).iterator();
    if (cur == null || !cur.hasNext())
        return 0;

    long id = 0;/* w w w .ja  v  a2 s . c om*/
    while (cur.hasNext()) {
        Document d = (Document) cur.next();
        Object t = d.get("id");
        if (t == null)
            continue;
        long i = AjaxTool.ToLong(t + "");
        if (i > id)
            id = i;
    }
    return id;
}