Java Code Examples for com.mongodb.client.MongoCollection.find()

The following are Jave code examples for showing how to use find() of the com.mongodb.client.MongoCollection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: mongodb-crud   File: QueryDocumentsImpl.java   Source Code and License Vote up 10 votes
/**
 * 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);
    }
}
 
Example 2
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: FlowerRating.java   Source Code and License Vote up 7 votes
@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"));
}
 
Example 3
Project: dooo   File: MongodbDataAccess.java   Source Code and License Vote up 7 votes
/**
 * 查询
 *
 * @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;
}
 
Example 4
Project: dooo   File: MongodbDataAccess.java   Source Code and License Vote up 7 votes
/**
 * 查询并逐条处理
 *
 * @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();
    }
}
 
Example 5
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   Source Code and License Vote up 7 votes
@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());
    }
}
 
Example 6
Project: Jerkoff   File: MongoDBDaoImpl.java   Source Code and License Vote up 6 votes
@Override
public List<Document> find(String collection, String signature) {
	List<Document> res = new ArrayList<Document>();
	try {
		MongoDatabase db = mongoClient.getDatabase(databaseName);
		MongoCollection<Document> coll = db.getCollection(collection);
		BasicDBObject searchQuery = new BasicDBObject();
		searchQuery.put("signature", signature);
		Iterable<Document> docs = coll.find(searchQuery);
		for (Document doc : docs) {
			res.add(doc);
		}
	} catch (Exception e) {
		LOG.error(e);
	}
	return res;
}
 
Example 7
Project: dooo   File: SimpleMongodbAccessor.java   Source Code and License Vote up 6 votes
/**
 * 查找指定条数的数据
 */
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;
}
 
Example 8
Project: Jerkoff   File: MongoTest.java   Source Code and License Vote up 6 votes
@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();
    }
}
 
Example 9
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: TestBedController.java   Source Code and License Vote up 6 votes
@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());

}
 
Example 10
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: FlowerRating.java   Source Code and License Vote up 6 votes
@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"));
}
 
Example 11
Project: digital-display-garden-iteration-4-dorfner-v2   File: FlowerRating.java   Source Code and License Vote up 6 votes
@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);
}
 
Example 12
Project: dooo   File: MongodbDataAccess.java   Source Code and License Vote up 5 votes
/**
 * 查询
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort           排序方式
 * @param pageInfo       分页
 * @return
 */
public List<Map<String, Object>> find(
        String collectionName,
        MongodbQuery query, MongodbFields fields,
        MongodbSort sort, MongodbPageInfo pageInfo) {
    List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
    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());
    }
    if (pageInfo != null) {
        int startPos = pageInfo.getPageIndex() * pageInfo.getPageSize();
        int rows = pageInfo.getPageSize();
        if (startPos > 0) {
            findIterable.skip(startPos - 1);
        }
        findIterable.limit(rows);
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Map<String, Object> document = cursor.next();
            resultMapList.add(document);
        }
    } finally {
        cursor.close();
    }

    return resultMapList;
}
 
Example 13
Project: osm-processor   File: MongoStore.java   Source Code and License Vote up 5 votes
/**
 * Find all documents of a collection, matching the passed filter
 * 
 * @param collectionName name of the collection
 * @param filter filtering criteria
 * 
 * @return {@link FindIterable} of documents.
 */
public FindIterable<Document> find(final String collectionName, final Document filter) {
    // Sanity checks
    if (StringUtils.isEmpty(collectionName)) {
        throw new IllegalArgumentException("find :: Collection name should not be blank");
    }

    MongoCollection<Document> collection = this.database.getCollection(collectionName);
    FindIterable<Document> result = collection.find(filter);

    return result;
}
 
Example 14
Project: dooo   File: MongodbDataAccess.java   Source Code and License Vote up 5 votes
/**
 * 查询并逐条处理
 *
 * @param clazz          类
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort           排序方式
 * @param consumer       记录处理
 * @param <T>
 * @return
 */
public <T> void findAndConsumer(
        Class<T> clazz, String collectionName,
        MongodbQuery query, MongodbFields fields,
        MongodbSort sort, Consumer<T> 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()) {
            Document document = cursor.next();
            T model = JSON.parseObject(JSON.toJSONString(document), clazz);
            consumer.accept(model);
        }
    } finally {
        cursor.close();
    }

}
 
Example 15
Project: dooo   File: MongodbDataAccess.java   Source Code and License Vote up 5 votes
/**
 * 查询
 *
 * @param clazz          类
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort           排序方式
 * @param <T>
 * @return
 */
public <T> List<T> find(
        Class<T> clazz, String collectionName,
        MongodbQuery query, MongodbFields fields,
        MongodbSort sort, MongodbPageInfo pageInfo) {
    List<T> resultMapList = new ArrayList<T>();
    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());
    }
    if (pageInfo != null) {
        int startPos = pageInfo.getPageIndex() * pageInfo.getPageSize();
        int rows = pageInfo.getPageSize();
        if (startPos > 0) {
            findIterable.skip(startPos - 1);
        }
        findIterable.limit(rows);
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Document document = cursor.next();
            T model = JSON.parseObject(JSON.toJSONString(document), clazz);
            resultMapList.add(model);
        }
    } finally {
        cursor.close();
    }

    return resultMapList;
}
 
Example 16
Project: nectar-server   File: AuthController.java   Source Code and License Vote up 4 votes
@RequestMapping(NectarServerApplication.ROOT_PATH + "/auth/removeUser")
public ResponseEntity removeUser(@RequestParam(value = "token") String jwtRaw, @RequestParam(value = "user") String username, HttpServletRequest request) {
    ResponseEntity r = Util.verifyJWT(jwtRaw, request);
    if(r != null)
        return r;

    ManagementSessionToken token = ManagementSessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
    if(token == null)
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");

    if(SessionController.getInstance().checkManagementToken(token)) {
        MongoCollection<Document> users = NectarServerApplication.getDb().getCollection("users");
        MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");

        // Check that the user exists
        Document clientDoc = users.find(Filters.eq("username", username)).first();
        if(clientDoc == null)
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Username not found in database!");

        // Check that the user is not signed in
        FindIterable<Document> clientsWithUserSignedIn = clients.find(Filters.eq("loggedInUser", username));
        if(clientsWithUserSignedIn.first() != null)
            return ResponseEntity.status(HttpStatus.CONFLICT).body("The user is currently signed into a client!");

        // Delete the user entry in the database
        users.deleteOne(Filters.eq("username", username));

        // Remove the user's FTS store

        File storeLocation = new File(NectarServerApplication.getConfiguration().getFtsDirectory() + File.separator
                + "usrStore" + File.separator + username
        );

        try {
            FileUtils.deleteDirectory(storeLocation);
        } catch (IOException e) {
            NectarServerApplication.getLogger().warn("Failed to delete FTS store for former user \"" + username + "\"");
            NectarServerApplication.getEventLog().addEntry(EventLog.EntryLevel.WARNING, "Failed to delete FTS store while deleting user " + username);
        }

        NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.INFO, "Removed user \"" + username + "\" by MANAGEMENT SESSION: " + token.getClientIP());
    } else {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Success.");
}
 
Example 17
Project: MooProject   File: DatabaseConnection.java   Source Code and License Vote up 4 votes
public FindIterable<Document> findSync(MongoCollection<Document> collection, Bson filter, int limit) {
    if(filter != null) return collection.find(filter).limit(limit);
    else return collection.find();
}
 
Example 18
Project: otus_java_2017_06   File: MongoMain.java   Source Code and License Vote up 4 votes
private FindIterable<Document> findById(String collectionName, ObjectId id) {
    MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", id);
    return collection.find(searchQuery);
}
 
Example 19
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: TestBedController.java   Source Code and License Vote up 4 votes
@Test
public void TestQRScansAndQRVisits(){
    //first lets test qr scans
    bedController.incrementBedMetadata("7.0","qrScans","second uploadId");
    MongoCollection beds = testDB.getCollection("beds");

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

    int qrScans =  (int)((Document) result.get("metadata")).get("qrScans");

    assertEquals("this bed should have been scanned once ",1, qrScans);


    //now we have 1 qrScan for this gardenLocation so the next method that is called should have 2 scans but
    // report only 1 scan in qrVisits Document

    // make sure that qr bed visits works
    bedController.addBedQRVisit("7.0","second uploadId");

    FindIterable doc1 = beds.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd302")));
    Iterator iterator1 = doc1.iterator();
    Document result1 = (Document) iterator1.next();

    List<Document> qrVisits =  (List<Document>)((Document) result1.get("metadata")).get("qrVisits");
    int qrScans2 =  (int) ((Document)result1.get("metadata")).get("qrScans");

    //should also increment the pageViews as it is actually visiting the page
    int pageViews =  (int) ((Document)result1.get("metadata")).get("pageViews");
    assertEquals("this should have 1 visit via qr scanning",1 ,qrVisits.size());

    Document qrvisit = qrVisits.get(0);
    ObjectId objectId = new ObjectId();

    String s = qrvisit.get("scan").toString();

    //after already having 1 qr scan the qr visit should increment qrScans
    assertEquals("there should be two qr scans now",2,qrScans2);
    assertEquals("there should be one pageView via the qr scanned ",1,pageViews);
    //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(),qrvisit.get("scan").getClass().getName());
    assertEquals("the object id produced from a visit must be 24 characters",24,s.length());
}
 
Example 20
Project: Smart_City   File: ReportDAO.java   Source Code and License Vote up 4 votes
protected static FindIterable<Document> findReports() {
    MongoDatabase db = Configurator.INSTANCE.getDatabase();
    MongoCollection collection = db.getCollection(COLLECTION);
    
    return collection.find();
}