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

The following are Jave code examples for showing how to use count() 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.
+ Save this method
Example 1
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: TestPlantComment.java   View Source Code Vote up 6 votes
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.storePlantComment(json, "second uploadId"));

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

    long contains = commentDocuments.count();
    assertEquals(1, contains);

    Iterator<Document> iter = commentDocuments.find().iterator();

    Document fromDb = iter.next();

    assertEquals("Here is our comment for this test", fromDb.getString("comment"));
    assertEquals("16040.0", fromDb.get("commentOnPlant"));
    assertEquals("second uploadId", fromDb.get("uploadId"));
}
 
Example 2
Project: Indra   File: MongoVectorSpace.java   View Source Code Vote up 6 votes
private void configure() {
    MongoDatabase db = this.mongoClient.getDatabase(dbName);
    MongoCollection<Document> metadataColl = db.getCollection(METADATA_COLL_NAME);

    if (metadataColl.count() > 1) {
        throw new IndraError("Model metadata must have only one entry!");
    }

    if (metadataColl.count() == 1) {
        logger.debug("Using stored metadata of {}", dbName);
        Document storedMetadata = metadataColl.find().first();
        metadata = ModelMetadata.createFromMap(storedMetadata);
    }
    else {
        logger.debug("No metadata found in {}, using defaults.", dbName);
        metadata = ModelMetadata.createDefault();
    }

    logger.info("Model metadata: {}", metadata);
}
 
Example 3
Project: uavstack   File: MongoDBDataStore.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
private List<Map> countAction(DataStoreMsg msg, Map queryparmes, MongoCollection<Document> collection) {

    BasicDBObject query = new BasicDBObject();// output

    Map findparmes = (Map) queryparmes.get(DataStoreProtocol.WHERE);
    QueryStrategy qry = new QueryStrategy();
    Map express = new LinkedHashMap();
    express.put(DataStoreProtocol.FIND, findparmes);
    qry.concretProcessor(DataStoreProtocol.FIND, express, query);

    // for (Object qobj : query.keySet()) {
    // log.info(this, "shell in package:" + qobj.toString() + ":" + query.get(qobj));
    // }

    log.info(this, "MongoDBDataStore countAction toJson : " + query.toJson());

    long countN = collection.count(query);
    Map<String, Object> item = new LinkedHashMap<String, Object>();
    item.put(DataStoreProtocol.COUNT, countN);
    List<Map> res = new ArrayList<Map>();
    res.add(item);

    return res;

}
 
Example 4
Project: grain   File: MongodbManager.java   View Source Code Vote up 5 votes
/**
 * 获取个数
 * 
 * @param collectionName
 *            表名
 * @param filter
 *            过滤
 * @return
 */
public static long count(String collectionName, Bson filter) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		if (filter == null) {
			return collection.count();
		} else {
			return collection.count(filter);
		}
	} catch (Exception e) {
		if (log != null) {
			log.error("查询个数失败", e);
		}
		return 0;
	}

}
 
Example 5
Project: QDrill   File: MongoGroupScan.java   View Source Code Vote up 5 votes
@Override
public ScanStats getScanStats() {
  try{
    MongoClient client = storagePlugin.getClient();
    MongoDatabase db = client.getDatabase(scanSpec.getDbName());
    MongoCollection<Document> collection = db.getCollection(scanSpec
        .getCollectionName());
    String json = collection.find().first().toJson();
    float approxDiskCost = json.getBytes().length * collection.count();
    return new ScanStats(GroupScanProperty.EXACT_ROW_COUNT,
        collection.count(), 1, approxDiskCost);
  } catch (Exception e) {
    throw new DrillRuntimeException(e.getMessage(), e);
  }
}
 
Example 6
Project: osm-processor   File: MongoStore.java   View Source Code Vote up 5 votes
/**
 * Count the documents of a collection.
 * 
 * @param collectionName name of the collection to insert the document in to.
 * @return total no. of documents of a collection.
 */
public long count(final String collectionName) {
    // Sanity checks
    if (StringUtils.isEmpty(collectionName)) {
        throw new IllegalArgumentException("count :: Collection name should not be blank");
    }

    // Collection
    MongoCollection<Document> collection = this.database.getCollection(collectionName);
    return collection.count();
}
 
Example 7
Project: intellead-integration-tests   File: Steps.java   View Source Code Vote up 5 votes
@Then("^Lead with id (\\d+) should be in the database")
public void Lead_with_id_should_be_in_intellead_data_mongodb_database(int leadId) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    long count = collection.count(parse("{_id: {$eq: \"" + leadId + "\"}}"));
    assertEquals(1, count);
}
 
Example 8
Project: intellead-integration-tests   File: Steps.java   View Source Code Vote up 5 votes
@Then("^Lead with ([\\w_\\.]+) equals to ([\\w ]+) should be in the database")
public void Lead_with_field_should_be_in_intellead_data_mongodb_database(String fieldName, String fieldValue) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    long count = collection.count(parse("{\"" + fieldName + "\": {$eq: \"" + fieldValue + "\"}}"));
    assertTrue(count >= 1);
}
 
Example 9
Project: intellead-integration-tests   File: Steps.java   View Source Code Vote up 5 votes
@Then("^Lead with id (\\d+) has field ([\\w_\\.]+) in the database$")
public void Lead_with_id_has_field_in_the_database(int leadId, String fieldName) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    long count = collection.count(parse("{$and: [{_id: {$eq: \"" + leadId + "\"}}, {\"" + fieldName + "\": {$exists: true}}]}"));
    assertEquals(1, count);
}
 
Example 10
Project: intellead-integration-tests   File: Steps.java   View Source Code Vote up 5 votes
@Then("^Delete lead with id (\\d+) in the database")
public void Delete_lead_with_id_in_intellead_data_mongodb_database(int leadId) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    collection.deleteOne(parse("{_id: {$eq: \"" + leadId + "\"}}"));
    long count = collection.count(parse("{_id: {$eq: \"" + leadId + "\"}}"));
    assertEquals(0, count);
}
 
Example 11
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: TestPlantComment.java   View Source Code Vote up 5 votes
@Test
public void failedInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd27\", comment : \"Here is our comment for this test\" }";

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

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

    long contains = commentDocuments.count();
    assertEquals(0, contains);
}
 
Example 12
Project: Mp3Bib   File: Database.java   View Source Code Vote up 5 votes
private int getLargestID() throws NotConnectedException {
    try {
        MongoCollection<Document> collection = getCollection();
        if (collection.count() <= 0) {
            return 0;
        }
        int largestID = (int) collection.find().sort(Sorts.descending("internalDbID")).limit(1).first().get("internalDbID");
        return largestID;
    } catch (Exception e) {
        BackendprocessService.getInstance().logger.error("couldnt find largest id " + e.toString());
    }
    return 1;
}
 
Example 13
Project: rocketmq-flink-plugin   File: MongoManager.java   View Source Code Vote up 5 votes
public JSONObject executeCount(String dbName, String collectionName, JSONObject reqJson) {

        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);

        JSONObject resp = new JSONObject();
        Document doc = Document.parse(reqJson.toString());
        long count = coll.count(doc);
        resp.put("Data", count);
        return resp;
    }
 
Example 14
Project: digital-display-garden-iteration-2-spraguesanborn   File: ExcelParser.java   View Source Code Vote up 5 votes
private static void createBeds(String[][] plants) {
    String[] keys = getKeys(plants);
    int bedCol = 1;
    for (int i = 0; i < keys.length; i++){
        if (keys[i].equals("gardenLocation")){
            bedCol = i;
            break;
        }
    }

    MongoClient mongoClient = new MongoClient();
    MongoDatabase ddg = mongoClient.getDatabase("ddg");
    MongoCollection beds = ddg.getCollection("beds");
    beds.drop();

    for (int i = 4; i < plants.length; i++){
        String currentBed = plants[i][bedCol];

        Bson filter = new Document("gardenLocation", currentBed);


        if (beds.count(filter) == 0 && !currentBed.equals("")) {
            Document doc = new Document("gardenLocation", currentBed);

            beds.insertOne(doc);
        }
    }
}
 
Example 15
Project: wechat-mall   File: MongoCRUD.java   View Source Code Vote up 4 votes
public static int getCount(MongoCollection<Document> col) {
    int count = (int) col.count();
    return count;
}
 
Example 16
Project: MooProject   File: DatabaseConnection.java   View Source Code Vote up 4 votes
public long count(MongoCollection<Document> collection) {
    return collection.count();
}
 
Example 17
Project: MooProject   File: DatabaseConnection.java   View Source Code Vote up 4 votes
public long count(MongoCollection<Document> collection, Bson filter) {
    return collection.count(filter);
}
 
Example 18
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: TestPlantComment.java   View Source Code Vote up 4 votes
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"16040.0\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.storePlantComment(json, "second uploadId"));

    MongoCollection<Document> commentDocuments = testDB.getCollection("comments");

    long contains = commentDocuments.count();
    assertEquals(1, contains);

    Iterator<Document> iter = commentDocuments.find().iterator();

    Document fromDb = iter.next();

    assertEquals("Here is our comment for this test", fromDb.getString("comment"));
    assertEquals("16040.0", fromDb.get("commentOnPlant"));
    assertEquals("second uploadId", fromDb.get("uploadId"));
}
 
Example 19
Project: Babler   File: DAO.java   View Source Code Vote up 2 votes
/**
 *
 * @param c class to count
 * @param source where data was collected from
 * @param language
 * @return count of all documents in db
 */
public static long countBySourceAndLanguage(Class c, String source, String language) {
    MongoCollection collection = getCollectionForClass(c);
    return collection.count(and(eq("collectedFrom", source), eq("languageCode", language)));
}
 
Example 20
Project: Babler   File: DAO.java   View Source Code Vote up 2 votes
/**
 * returns count of number of docs belonging to collection
 *
 * @param collectionName
 * @param dbName
 * @return count of docs in collection
 */
public static long getCollectionCountInLanguage(String collectionName, String dbName) {
    MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName, BasicDBObject.class);
    return collection.count();
}