當前位置: 首頁>>代碼示例>>Java>>正文


Java MongoCollection.find方法代碼示例

本文整理匯總了Java中com.mongodb.client.MongoCollection.find方法的典型用法代碼示例。如果您正苦於以下問題:Java MongoCollection.find方法的具體用法?Java MongoCollection.find怎麽用?Java MongoCollection.find使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.mongodb.client.MongoCollection的用法示例。


在下文中一共展示了MongoCollection.find方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getAllDocuments

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:19,代碼來源:QueryDocumentsImpl.java

示例2: AddFlowerRatingReturnsTrueWithValidInput

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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"));
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-revolverenguardia-1,代碼行數:18,代碼來源:FlowerRating.java

示例3: findAll

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 查詢
 *
 * @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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:30,代碼來源:MongodbDataAccess.java

示例4: findAndConsumer

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 查詢並逐條處理
 *
 * @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();
    }
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:35,代碼來源:MongodbDataAccess.java

示例5: failedInputOfComment

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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());
    }
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:19,代碼來源:TestPlantComment.java

示例6: find

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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;
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:18,代碼來源:MongoDBDaoImpl.java

示例7: find

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 查找指定條數的數據
 */
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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:27,代碼來源:SimpleMongodbAccessor.java

示例8: testRead

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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();
    }
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:25,代碼來源:MongoTest.java

示例9: TestBedVisit

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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());

}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-revolverenguardia-1,代碼行數:26,代碼來源:TestBedController.java

示例10: AddFlowerRatingReturnsTrueWithValidJsonInput

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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"));
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-3-sixguysburgers-fries,代碼行數:23,代碼來源:FlowerRating.java

示例11: AddFlowerRatingReturnsTrueWithValidInput

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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);
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:20,代碼來源:FlowerRating.java

示例12: find

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 查詢
 *
 * @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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:46,代碼來源:MongodbDataAccess.java

示例13: find

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:millij,項目名稱:osm-processor,代碼行數:20,代碼來源:MongoStore.java

示例14: removeUser

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@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.");
}
 
開發者ID:jython234,項目名稱:nectar-server,代碼行數:48,代碼來源:AuthController.java

示例15: findSync

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public FindIterable<Document> findSync(MongoCollection<Document> collection, Bson filter, int limit) {
    if(filter != null) return collection.find(filter).limit(limit);
    else return collection.find();
}
 
開發者ID:Superioz,項目名稱:MooProject,代碼行數:5,代碼來源:DatabaseConnection.java


注:本文中的com.mongodb.client.MongoCollection.find方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。