Java 类com.mongodb.client.FindIterable 实例源码

项目:mongodb-crud    文件:QueryDocumentsImpl.java   
/**
 * This method retrieve all the document(s)
 */
@Override
public void getAllDocuments() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> docs = collection.find(); //SELECT * FROM sample;
        for (Document doc : docs) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert Value using **BasicDBObject** : " + e, e);
    }
}
项目:Smart_City    文件:ReportDAO.java   
public static JSONObject findReportsRaw() {
    JSONArray reports = new JSONArray();
    FindIterable<Document> result = findReports();

    result.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            JSONObject jsonReport = new JSONObject();
            jsonReport.put("id", document.getObjectId("_id").toString());
            jsonReport.put("comment", document.getString("comment"));
            jsonReport.put("city_item_id", document.getString("city_item_id"));
            jsonReport.put("priority", document.getInteger("priority"));
            jsonReport.put("resolved", document.getBoolean("resolved"));
            jsonReport.put("report_date", document.getLong("report_date"));
            reports.put(jsonReport);
        }
    });

    JSONObject jsonResults = new JSONObject();
    jsonResults.put("reports", reports);

    return jsonResults;
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidInput() throws IOException{

    assertTrue(plantController.addFlowerRating("16001.0", true, "first uploadId"));
    MongoCollection plants = testDB.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    //assertTrue(rating.getBoolean("like"));
    //assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"16001.0\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId"));

    MongoCollection plants = testDB.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:TestBedController.java   
@Test
public void TestBedVisit(){
    bedController.addBedVisit("10.0","first uploadId");
    MongoCollection beds = testDB.getCollection("beds");

    FindIterable doc = beds.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd303")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();
    //System.out.println(result);

    List<Document> bedVisits =  (List<Document>)((Document) result.get("metadata")).get("bedVisits");
    //System.out.println(bedVisits);
    assertEquals("",1 ,bedVisits.size());

    Document visits = bedVisits.get(0);
    //System.out.println(visits.get("visit"));
    ObjectId objectId = new ObjectId();

    String v = visits.get("visit").toString();

    //checking to see that the type of visit is an of type/structure of ObjectID
    assertEquals("they should both be of type org.bson.types.ObjectId ",objectId.getClass().getName(),visits.get("visit").getClass().getName());
    assertEquals("the object id produced from a visit must be 24 characters",24,v.length());

}
项目:j1st-mqtt    文件:MongoStorage.java   
/**
 * 根据Operator订购的服务类型来查询可用数量(未过期的)
 *
 * @param serviceType service type
 * @param operatorId  operator ID
 * @return number of service
 */
public long getServiceCountByOperatorId(Integer serviceType, ObjectId operatorId) {
    long count = 0;
    Document query = new Document();
    query.append("user_id", operatorId);
    query.append("serviceType", serviceType);
    query.append("expired_at", new Document("$gte", new Date()));
    FindIterable<Document> ds = this.database.getCollection("user_services").find(query);
    if (ds != null) {
        for (Document d : ds) {
            if (d.getLong("used") != null) {
                count += d.getLong("count") - d.getLong("used");
            } else {
                count += d.getLong("count");
            }
        }
    }
    return count;
}
项目:Smart_City    文件:ReportDAO.java   
/**
 * Returns all reports for view
 * 
 * @return List
 */
public static List<ReportViewObject> findReportsForView() {
    List<ReportViewObject> reports = new ArrayList<>();
    FindIterable<Document> result = findReports();

    result.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            Report.Builder b = new Report.Builder();
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            String reportDate = df.format(new Date(document.getLong("report_date")));

            reports.add(new ReportViewObject(
                    document.getObjectId("_id").toString(),
                    Integer.toString(document.getInteger("priority")),
                    document.getString("city_item_id"),
                    reportDate,
                    document.getBoolean("resolved") ? "YES" : "NO"));
        }
    });

    return reports;
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidInput() throws IOException{

    assertTrue(plantController.addFlowerRating("58d1c36efb0cac4e15afd202", true, "first uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:Indra    文件:MongoVectorSpace.java   
@Override
protected void collectVectors(Collection<String> terms, int limit) {
    Set<String> toFetch = terms.stream()
            .filter(t -> !this.vectorsCache.containsKey(t))
            .collect(Collectors.toSet());

    logger.debug("Cache has {} vectors, need to fetch more {}",
            terms.size() - toFetch.size(), toFetch.size());

    if (!toFetch.isEmpty()) {
        logger.info("Collecting {} term vectors from {}", toFetch.size(), dbName);
        FindIterable<Document> docs = getTermsColl().find(Filters.in(TERM_FIELD_NAME, toFetch));
        if (docs != null) {
            docs.batchSize(toFetch.size());
            for (Document doc : docs) {
                this.vectorsCache.put(doc.getString(TERM_FIELD_NAME), unmarshall(doc, limit));
            }
        }
    }
}
项目:Indra    文件:MongoIndraTranslator.java   
private Map<String, List<String>> doTranslate(Set<String> tokens) {
    MongoCollection<Document> lexColl = getLexCollection();
    FindIterable<Document> lexs = lexColl.find(Filters.in(TERM_FIELD, tokens));

    Map<String, List<String>> res = new HashMap<>();
    for (Document doc : lexs) {
        Document tr = (Document) doc.get(TRANSLATION_FIELD);

        if (tr != null) {
            tr.remove(NULL_VALUE);
            res.put(doc.getString(TERM_FIELD), getRelevantTranslations((Map) tr));
        }
    }

    return res;
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:TestPlantComment.java   
@Test
public void failedInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd27\", comment : \"Here is our comment for this test\" }";

    assertFalse(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    FindIterable findIterable = plants.find();
    Iterator iterator = findIterable.iterator();
    while(iterator.hasNext()){
        Document plant = (Document) iterator.next();
        List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
        assertEquals(0,plantComments.size());
    }
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidInput() throws IOException{
    assertTrue(plantController.addFlowerRating("58d1c36efb0cac4e15afd202", true, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
项目:mongodb-rdbms-sync    文件:MngToOrclReader.java   
@Override
public void run() {
    System.out.println("Reader started");
    MongoCollection<Document> collection = DBCacheManager.INSTANCE.getCachedMongoPool(mongoDbName, mongoUserName)
            .getDatabase(mongoDbName).getCollection(collectionName);
    FindIterable<Document> it = collection.find().batchSize(batchSize);
    it.forEach(new Block<Document>() {
        @Override
        public void apply(Document t) {
            System.out.println("Document read " + t);
            try {
                dataBuffer.put(t);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
项目:BingoChess    文件:BingoChess.java   
public String raffle(boolean mock) {
    FindIterable<Document> docs = playData.find();
    ArrayList<String> playBag = new ArrayList<String>();
    for (Document doc : docs) {
        String name = doc.getString("name");
        int tickets = doc.getInteger("tickets");
        for (int i=0; i < tickets; i++) {
            playBag.add(name);
        }
        if (!mock) {
            playData.updateOne(eq("name",name),set("tickets",0));
            playData.updateOne(eq("name",name),set("gold",100));
        }
    }
    if (playBag.size() > 0) {
        Collections.shuffle(playBag);
        return playBag.get(0);
    }
    else return null;
}
项目:Jerkoff    文件:MongoTest.java   
@Test
@Ignore
public void testRead() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        FindIterable<Document> res = coll.find();
        for (Document doc : res) {
            String thisObj = doc.getString("this");
            LOG.info(thisObj);
            String thisClass = doc.getString("thisClass");
            LOG.info(thisClass);
            Gson gson = new Gson();
            Class<?> cl = Class.forName(thisClass);
            Object obj = gson.fromJson(thisObj, cl);
            LOG.info(obj);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
项目:polymorphia    文件:PolymorphicTest.java   
/************  DOMAIN MODEL END ************/


    @Test
    public void polymorphiaTest() {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        MongoCollection<Shape> collection = database.getCollection("entities").withDocumentClass(Shape.class);


        Shape[] shapes = {new Circle(), new Square(), new Square(), new Circle()};
        collection.insertMany(Arrays.asList(shapes));

        FindIterable<Shape> shapesFoundIterable = collection.find();
        List<Shape> foundShapes = new ArrayList<>();
        for (Shape shape : shapesFoundIterable) {
            LOGGER.info("Found shape {} of type {} in database", shape, shape.getClass().getSimpleName());
            foundShapes.add(shape);
        }

        MatcherAssert.assertThat(foundShapes, CoreMatchers.hasItems(shapes));
    }
项目:dooo    文件:SimpleMongodbAccessor.java   
/**
 * 查找指定条数的数据
 */
public <T> List<T> find(String collectionName, Integer pageNumber, Integer pageSize, Class<T> clazz) {
    MongoCollection collection = mongoDatabase.getCollection(collectionName);
    List<T> list = new ArrayList<>();
    if (collection == null) {
        return list;
    }
    FindIterable findIterable = collection.find();

    if (pageSize != null && pageSize >= 0) {
        if (pageNumber != null && pageNumber >= 1) {
            findIterable = findIterable.skip((pageNumber - 1) * pageSize);
        }
        findIterable = findIterable.limit(pageSize);
    }
    Iterator<Document> iterator = findIterable.iterator();
    while (iterator.hasNext()) {
        Document document = iterator.next();
        document.remove("_id");
        T t = JSON.parseObject(document.toJson(), clazz);
        list.add(t);
    }
    return list;
}
项目:dooo    文件:SimpleMongodbAccessor.java   
/**
 * 查找指定条数的数据
 */
public List<Map<String, Object>> find(String collectionName, Integer pageNumber, Integer pageSize) {
    MongoCollection collection = mongoDatabase.getCollection(collectionName);
    List<Map<String, Object>> list = new ArrayList<>();
    if (collection == null) {
        return list;
    }
    FindIterable findIterable = collection.find();

    if (pageSize != null && pageSize >= 0) {
        if (pageNumber != null && pageNumber >= 1) {
            findIterable = findIterable.skip((pageNumber - 1) * pageSize);
        }
        findIterable = findIterable.limit(pageSize);
    }
    Iterator<Document> iterator = findIterable.iterator();
    while (iterator.hasNext()) {
        Document document = iterator.next();
        document.remove("_id");
        Map<String, Object> map = new HashMap<>(document);
        list.add(map);
    }
    return list;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询并逐条处理
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort           排序方式
 * @param consumer       记录处理
 * @return
 */
public void findAndConsumer(
        String collectionName,
        MongodbQuery query, MongodbFields fields,
        MongodbSort sort, Consumer<Map<String, Object>> consumer) {
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find(query == null ? new Document() : query.getQuery());
    if (fields == null) {
        findIterable.projection(new MongodbFields().getDbObject());
    } else {
        findIterable.projection(fields.getDbObject());
    }
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Map<String, Object> document = cursor.next();
            consumer.accept(document);
        }
    } finally {
        cursor.close();
    }
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询
 *
 * @param clazz          类
 * @param collectionName 集合名
 * @param sort           排序
 * @param <T>
 * @return
 */
public <T> List<T> findAll(Class<T> clazz, String collectionName, MongodbSort sort) {
    List<T> resultMapList = new ArrayList<T>();
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find();
    if(sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Document document = cursor.next();
            T parseObject = JSON.parseObject(JSON.toJSONString(document), clazz);
            resultMapList.add(parseObject);
        }
    } finally {
        cursor.close();
    }

    return resultMapList;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询
 *
 * @param collectionName 集合名
 * @param sort           排序方式
 * @return
 */
public List<Map<String, Object>> findAll(String collectionName, MongodbSort sort) {
    List<Map<String, Object>> resultMapList = new ArrayList<>();
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find();
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Document document = cursor.next();
            resultMapList.add(document);
        }
    } finally {
        cursor.close();
    }

    return resultMapList;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询一个
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort
 * @return
 */
public Map<String, Object> findOne(
        String collectionName,
        MongodbQuery query, MongodbFields fields, MongodbSort sort) {
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find(query.getQuery());
    if (fields == null) {
        findIterable.projection(new MongodbFields().getDbObject());
    } else {
        findIterable.projection(fields.getDbObject());
    }
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    findIterable.limit(1);
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        if (cursor.hasNext()) {
            return cursor.next();
        }
    } finally {
        cursor.close();
    }
    return null;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询一个
 *
 * @param clazz          类
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort
 * @param <T>
 * @return
 */
public <T> T findOne(
        Class<T> clazz, String collectionName,
        MongodbQuery query, MongodbFields fields, MongodbSort sort) {
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find(query.getQuery());
    if (fields == null) {
        findIterable.projection(new MongodbFields().getDbObject());
    } else {
        findIterable.projection(fields.getDbObject());
    }
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    findIterable.limit(1);
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        if (cursor.hasNext()) {
            Document document = cursor.next();
            return JSON.parseObject(document.toJson(), clazz);
        }
    } finally {
        cursor.close();
    }
    return null;
}
项目:wildfly-nosql    文件:StatefulTestBean.java   
public String addUserComment() {
    MongoCollection collection = null;
    Document query = null;
    try {
        // add a comment from user Melanie
        String who = "Melanie";
        Document comment = new Document("_id", who)
                .append("name", who)
                .append("address", new BasicDBObject("street", "123 Main Street")
                        .append("city", "Fastville")
                        .append("state", "MA")
                        .append("zip", 18180))
                .append("comment", "MongoDB Is Web Scale");
        // save the comment
        collection = database.getCollection("comments");
        collection.insertOne(comment);

        // look up the comment from Melanie
        query = new Document("_id", who);
        FindIterable cursor = collection.find(query);
        Object userComment = cursor.first();
        return userComment.toString();
    } finally {
        collection.drop();
    }
}
项目:wildfly-nosql    文件:StatefulTestBean.java   
public String addSalesComment() {
    MongoCollection collection = null;
    Document query = null;
    try {
        // add a comment from Sales department
        String who = "InsideSalesTeam";
        Document comment = new Document("_id", who)
                .append("name", who)
                .append("address", new BasicDBObject("street", "inside sales")
                        .append("city", "internal")
                        .append("state", "internal")
                        .append("zip", 99999))
                .append("comment", "Need to sell sell sell");
        // save the comment
        collection = database.getCollection("comments");
        collection.insertOne(comment);

        query = new Document("_id", who);
        FindIterable cursor = collection.find(query);
        Object userComment = cursor.first();
        return userComment.toString();
    } finally {
        collection.drop();
    }
}
项目:wildfly-nosql    文件:StatefulTestBean.java   
public String addProduct() {
    MongoCollection collection = null;
    Document query = null;
    try {
        collection = injectedDatabase.getCollection("company");
        String companyName = "Acme products";
        JsonObject object = Json.createObjectBuilder()
                .add("companyName", companyName)
                .add("street", "999 Flow Lane")
                .add("city", "Indiville")
                .add("_id", companyName)
                .build();
        Document document = Document.parse(object.toString());
        collection.insertOne(document);
        query = new Document("_id", companyName);
        FindIterable cursor = collection.find(query);
        Object dbObject = cursor.first();
        return dbObject.toString();
    } finally {
        if (query != null) {
            collection.drop();
        }
    }
}
项目:wildfly-nosql    文件:StatefulTestBean.java   
public String addUserComment() {
    MongoCollection collection = null;
    Document query = null;
    try {
        // add a comment from user Melanie
        String who = "Melanie";
        Document comment = new Document("_id", who)
                .append("name", who)
                .append("address", new BasicDBObject("street", "123 Main Street")
                        .append("city", "Fastville")
                        .append("state", "MA")
                        .append("zip", 18180))
                .append("comment", "MongoDB Is Web Scale");
        // save the comment
        collection = database.getCollection("comments");
        collection.insertOne(comment);

        // look up the comment from Melanie
        query = new Document("_id", who);
        FindIterable cursor = collection.find(query);
        Object userComment = cursor.first();
        return userComment.toString();
    } finally {
        collection.drop();
    }
}
项目:wildfly-nosql    文件:StatefulTestBean.java   
public String addProduct() {
    MongoCollection collection = null;
    Document query = null;
    try {
        collection = injectedDatabase.getCollection("company");
        String companyName = "Acme products";
        JsonObject object = Json.createObjectBuilder()
                .add("companyName", companyName)
                .add("street", "999 Flow Lane")
                .add("city", "Indiville")
                .add("_id", companyName)
                .build();
        Document document = Document.parse(object.toString());
        collection.insertOne(document);
        query = new Document("_id", companyName);
        FindIterable cursor = collection.find(query);
        Object dbObject = cursor.first();
        return dbObject.toString();
    } finally {
        if (query != null) {
            collection.drop();
        }
    }
}
项目:otus-api    文件:ActivityDaoBean.java   
@Override
public List<SurveyActivity> findByCategory(String categoryName) {
    ArrayList<SurveyActivity> activities = new ArrayList<>();

    FindIterable<Document> result = collection.find(eq("category.name", categoryName));

    result.forEach((Block<Document>) document -> activities.add(SurveyActivity.deserialize(document.toJson())));
    return activities;
}
项目:FatJar    文件:MongoDB.java   
@Override
public <T> T find(Class<T> typeClass, Object primary) {
    T t = null;
    MongoCollection<Document> collection = database.getCollection(typeClass.getSimpleName());
    BasicDBObject query = new BasicDBObject(MongoModel.OID, primary);
    FindIterable<Document> documents = collection.find(query);
    Document document = documents.first();
    try {
        t = typeClass.newInstance();
        if (MongoModel.class.isAssignableFrom(typeClass)) {
            MongoModel mongoModel = (MongoModel) t;
            mongoModel.fromDocument(document);
        } else {
            Log.error("class is not an instance of MongoModel, will not be able to set document to T object, class: " + typeClass);
        }
    } catch (InstantiationException | IllegalAccessException e) {
        Log.error("could not create mongo model of class: " + typeClass + " got exception: " + e, e);
    }
    return t;
}
项目:pumbaa    文件:MongodbService.java   
private Object find(String filter) throws ServiceException {
    try {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        FindIterable<Document> cursor = null;
        if (filter != null) {
            BasicDBObject filterObj = BasicDBObject.parse(filter);
            cursor = this.collection.find(filterObj);
        } else {
            cursor = this.collection.find();
        }

        if (cursor != null) {
            MongoCursor<Document> iterator = cursor.iterator();
            while (iterator.hasNext()) {
                result.add(iterator.next());
            }
        }
        return result;
    } catch (Exception e) {
        throw new ServiceException("Search Exception: " + e.getMessage());
    }
}
项目:giiwa    文件:MongoHelper.java   
/**
 * load the data by the query.
 *
 * @param <T>
 *            the subclass of Bean
 * @param collection
 *            the collection name
 * @param query
 *            the query
 * @param b
 *            the Bean
 * @return the Bean
 */
public <T extends Bean> T load(String collection, Bson query, T b) {
    try {
        MongoCollection<Document> db = getCollection(collection);
        if (db != null) {
            FindIterable<Document> d = db.find(query);
            if (d != null) {
                Document d1 = d.first();
                if (d1 != null) {
                    b.load(d1, null);
                    return b;
                }
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled())
            log.error(e.getMessage(), e);
    }

    return null;
}
项目:mogodb-dao    文件:MongoAndSpringTest.java   
@Test
public void queryDataTest() {
    BasicDBObject fields = new BasicDBObject();
    fields.put("likes", new BasicDBObject("$gt", 16));
    FindIterable<Document> iterable = mongoPool.getDB()
            .getCollection("test").find(fields);
    MongoCursor<Document> cursor = iterable.iterator();
    System.out.println(cursor);
    while (cursor.hasNext()) {
        Document document = cursor.next();

        System.out.println(document);

        if (document.get("append") != null) {
            System.out.println(document.get("append") instanceof Document);
        }
    }
}
项目:Cotton    文件:MongoDBConnector.java   
/**
 * Returns data from the database.
 *
 * @param searchKeys JSONObject containing the information regarding what data the return needs to contain.
 * @return  returns an JSONObject containing desired data.
 */
@Override
public synchronized JSONObject getDataFromDatabase (JSONObject searchKeys){
    JSONArray retArray = new JSONArray();
    JSONObject returnValue = new JSONObject();

    BasicDBObject dbObject = (BasicDBObject) JSON.parse(searchKeys.toString());

    FindIterable<Document> request = db.getCollection("requestTable").find(dbObject);
    for(Document d: request){
        retArray.put(new JSONObject(d.toJson()));
    }

    returnValue.put("dataArray", retArray);
    return returnValue;
}
项目:Rapture    文件:MongoDbDataStore.java   
@Override
public String get(String k) {
    if (log.isDebugEnabled()) {
        log.debug("Get " + k); // Temporary to see what's up
    }
    MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName, tableName);
    Document query = new Document();
    query.put(KEY, k);
    FindIterable<Document> obj = collection.find(query).limit(1);
    if (obj != null) {
        for (Document doc : obj) {
            Object v = doc.get(VALUE);
            if (v != null) return v.toString();
        }
    }
    return null;
}
项目:Rapture    文件:MongoDBAuditLog.java   
@Override
public List<AuditLogEntry> getRecentEntries(final int count) {
    final Document sort = getSortObject();

    MongoRetryWrapper<List<AuditLogEntry>> wrapper = new MongoRetryWrapper<List<AuditLogEntry>>() {
        public FindIterable<Document> makeCursor() {
            return getAuditCollection().find().sort(sort).limit(count);
        }

        public List<AuditLogEntry> action(FindIterable<Document> cursor) {
            List<AuditLogEntry> ret = new ArrayList<AuditLogEntry>();
            fillFromCursor(ret, cursor);
            return ret;
        }
    };

    return wrapper.doAction();
}
项目:Rapture    文件:MongoDBAuditLog.java   
private void fillFromCursor(List<AuditLogEntry> ret, FindIterable<Document> cursor) throws MongoException {
    Iterator<Document> iterator = cursor.iterator();
    while (iterator.hasNext()) {
        Document obj = iterator.next();
        AuditLogEntry entry = new AuditLogEntry();
        entry.setLevel((Integer) obj.get(LEVEL));
        entry.setMessage(safeString(obj, MESSAGE));
        entry.setUser(safeString(obj, USER));
        entry.setLogId(safeString(obj, LOG_ID));
        entry.setWhen((Date) obj.get(WHEN));
        entry.setSource(safeString(obj, SOURCE));
        entry.setEntryId(safeString(obj, ENTRY_ID));
        entry.setCategory(safeString(obj, CATEGORY));
        ret.add(entry);
    }
}
项目:Rapture    文件:MongoDBAuditLog.java   
@Override
public List<AuditLogEntry> getEntriesSince(AuditLogEntry when) {
    final Document sort = getSortObject();
    final Document query = new Document();
    Document test = new Document();
    test.put("$gt", when.getWhen());
    query.put(WHEN, test);
    MongoRetryWrapper<List<AuditLogEntry>> wrapper = new MongoRetryWrapper<List<AuditLogEntry>>() {
        public FindIterable<Document> makeCursor() {
            return getAuditCollection().find(query).sort(sort);
        }

        public List<AuditLogEntry> action(FindIterable<Document> cursor) {
            List<AuditLogEntry> ret = new ArrayList<AuditLogEntry>();
            fillFromCursor(ret, cursor);
            return ret;
        }
    };
    return wrapper.doAction();
}