List of usage examples for com.mongodb.client MongoCollection count
@Deprecated
long count();
From source file:nl.mvdb.mongodb.RemoveStudentsLowestScore.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); try {// www. j a v a2 s . co m MongoDatabase database = client.getDatabase("students"); MongoCollection<Document> collection = database.getCollection("grades"); MongoCursor<Document> iterator = collection.find().sort(ascending("student_id", "score")).iterator(); Integer lastStudentId = null; while (iterator.hasNext()) { Document gradingDoc = iterator.next(); Integer studentId = gradingDoc.getInteger("student_id"); if (!studentId.equals(lastStudentId)) { lastStudentId = studentId; System.out.println(lastStudentId); collection.deleteOne(gradingDoc); } } System.out.println(collection.count()); } finally { client.close(); } }
From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java
License:Apache License
@Override public ScanStats getScanStats() { try {/*from w w w . j a v a 2 s.co m*/ MongoClient client = storagePlugin.getClient(); MongoDatabase db = client.getDatabase(scanSpec.getDbName()); MongoCollection<Document> collection = db.getCollection(scanSpec.getCollectionName()); long numDocs = collection.count(); float approxDiskCost = 0; if (numDocs != 0) { String json = collection.find().first().toJson(); approxDiskCost = json.getBytes().length * numDocs; } return new ScanStats(GroupScanProperty.EXACT_ROW_COUNT, numDocs, 1, approxDiskCost); } catch (Exception e) { throw new DrillRuntimeException(e.getMessage(), e); } }
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;// w w w . ja va 2 s.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.jaqpot.core.db.entitymanager.MongoDBEntityManager.java
License:Open Source License
@Override public <T extends JaqpotEntity> Long countAll(Class<T> entityClass) { MongoDatabase db = mongoClient.getDatabase(database); MongoCollection<Document> collection = db.getCollection(collectionNames.get(entityClass)); return collection.count(); }
From source file:org.lambda3.indra.mongo.MongoVectorSpace.java
License:Open Source License
@Override protected ModelMetadata loadMetadata() { MongoDatabase db = this.mongoClient.getDatabase(dbName); MongoCollection<Document> metadataColl = db.getCollection(METADATA_COLL_NAME); //TODO metadata needs to include CM if (metadataColl.count() > 1) { throw new IndraRuntimeException( "This model is misconfigured. Contact the support with the following message: model metadata has more than one entry."); }// w w w. ja v a 2s. c o m if (metadataColl.count() == 1) { logger.debug("Using stored metadata of {}", dbName); Document storedMetadata = metadataColl.find().first(); return new ModelMetadata(storedMetadata); } else { logger.debug("No metadata found in {}, using defaults.", dbName); //TODO throws an exception. //no default supported anymore. return null; } }
From source file:org.nuxeo.directory.mongodb.MongoDBDirectory.java
License:Apache License
@Override public Session getSession() throws DirectoryException { SchemaManager schemaManager = Framework.getService(SchemaManager.class); Schema schema = schemaManager.getSchema(getSchema()); if (schema == null) { throw new DirectoryException(getSchema() + " is not a registered schema"); }//ww w. ja v a 2 s . c o m schemaFieldMap = new LinkedHashMap<>(); schema.getFields().forEach(f -> schemaFieldMap.put(f.getName().getLocalName(), f)); MongoDBSession session = new MongoDBSession(this); addSession(session); // Initialize counters collection if autoincrement enabled if (descriptor.isAutoincrementIdField() && !session.hasCollection(countersCollectionName)) { Map<String, Object> seq = new HashMap<>(); seq.put(MONGODB_ID, getName()); seq.put(MONGODB_SEQ, 0L); session.getCollection(countersCollectionName).insertOne(MongoDBSerializationHelper.fieldMapToBson(seq)); } if (!initialized) { String policy = descriptor.getCreateTablePolicy(); MongoCollection collection = session.getCollection(getName()); boolean dropCollection = false; boolean loadData = false; switch (policy) { case CREATE_TABLE_POLICY_ALWAYS: dropCollection = true; loadData = true; break; case CREATE_TABLE_POLICY_ON_MISSING_COLUMNS: if (session.hasCollection(getName())) { long totalEntries = collection.count(); boolean missingColumns = schema.getFields().stream().map(f -> f.getName().getLocalName()) .anyMatch(fname -> collection.count(Filters.exists(fname, false)) == totalEntries); if (missingColumns) { dropCollection = true; loadData = true; } } else { loadData = true; } break; default: if (!session.hasCollection(getName())) { loadData = true; } break; } if (dropCollection) { collection.drop(); } if (loadData) { loadData(schema, session); } initialized = true; } return session; }
From source file:org.nuxeo.tools.esync.db.DbMongo.java
License:Open Source License
@Override public long getCardinality() { MongoCollection<org.bson.Document> table = getMongoCollection(); // The Root document is not returned by Es or VCS but by Mongo return table.count() - 1; }
From source file:org.restheart.db.CollectionDAO.java
License:Open Source License
/** * Checks if the given collection is empty. Note that RESTHeart creates a * reserved properties document in every collection (with _id * '_properties'). This method returns true even if the collection contains * such document.//from w w w. ja v a 2 s . c o m * * @param coll the mongodb DBCollection object * @return true if the commection is empty */ public boolean isCollectionEmpty(final MongoCollection<BsonDocument> coll) { return coll.count() == 0; }
From source file:rapture.table.mongodb.MongoIndexHandler.java
License:Open Source License
private void createIndex(IndexDefinition indexDefinition, boolean force) { // create index if not exists... use index name too from indexDefinition // object/*from w w w . ja v a2 s. c o m*/ if (indexDefinition == null) { return; } String indexName = IndexNameFactory.createIndexName(indexDefinition); MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName, tableName); int limit = Integer.parseInt(MultiValueConfigLoader.getConfig("MONGODB-" + instanceName + ".limit", MultiValueConfigLoader.getConfig("MONGODB-default.limit", "250"))); boolean indexExists = false; ListIndexesIterable<Document> indexInfo = collection.listIndexes(); for (Document dbObject : indexInfo) { Object name = dbObject.get("name"); if (name != null && name.toString().equals(indexName)) { indexExists = true; break; } } if (force || collection.count() < limit) { createIt(indexDefinition, force, indexName, collection); } else { if (!indexExists) { log.warn(tableName + " collection has more than " + limit + " items. please index manually"); } } }
From source file:result.analysis.Dbops.java
void CreateDb(String name) { try {//from ww w. j av a 2 s . com // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases MongoDatabase db = mongoClient.getDatabase(name);//must be there where csvparser is invoked System.out.println("Connect to database successfully"); MongoCollection<Document> collection = db.getCollection("test"); Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); System.out.println(collection.count()); Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }