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

The following examples show how to use com.mongodb.client.MongoCollection#count() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PutGridFSIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoUniqueness() {
    String fileName = "test_duplicates.txt";
    Map<String, String> attrs = new HashMap<>();
    attrs.put(CoreAttributes.FILENAME.key(), fileName);

    for (int x = 0; x < 10; x++) {
        runner.enqueue("Duplicates are ok.", attrs);
        runner.run();
    }

    runner.assertTransferCount(PutGridFS.REL_SUCCESS, 10);

    String bucketName = String.format("%s.files", BUCKET);
    MongoCollection files = client.getDatabase(DB).getCollection(bucketName);
    Document query = Document.parse(String.format("{\"filename\": \"%s\"}", fileName));
    long count = files.count(query);
    Assert.assertTrue("Wrong count", count == 10);
}
 
Example 2
Source File: MongoVectorSpace.java    From Indra with MIT License 6 votes vote down vote up
@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.");
    }

    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;
    }
}
 
Example 3
Source File: MongodbManager.java    From grain with MIT License 6 votes vote down vote up
/**
 * 获取个数
 * 
 * @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 4
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void removeStack(final StackId stackId,
                        final boolean includeMetaData)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final long tileCount = tileCollection.count();
    tileCollection.drop();

    LOG.debug("removeStack: {}.drop() deleted {} document(s)", MongoUtil.fullName(tileCollection), tileCount);

    final MongoCollection<Document> transformCollection = getTransformCollection(stackId);
    final long transformCount = transformCollection.count();
    transformCollection.drop();

    LOG.debug("removeStack: {}.drop() deleted {} document(s)",
              MongoUtil.fullName(transformCollection), transformCount);

    final MongoCollection<Document> sectionCollection = getSectionCollection(stackId);
    final long sectionCount = sectionCollection.count();
    sectionCollection.drop();

    LOG.debug("removeStack: {}.drop() deleted {} document(s)",
              MongoUtil.fullName(sectionCollection), sectionCount);

    if (includeMetaData) {
        final MongoCollection<Document> stackMetaDataCollection = getStackMetaDataCollection();
        final Document stackIdQuery = getStackIdQuery(stackId);
        final DeleteResult stackMetaDataRemoveResult = stackMetaDataCollection.deleteOne(stackIdQuery);

        LOG.debug("removeStack: {}.remove({}) deleted {} document(s)",
                  MongoUtil.fullName(stackMetaDataCollection),
                  stackIdQuery.toJson(),
                  stackMetaDataRemoveResult.getDeletedCount());
    }
}
 
Example 5
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return number of tiles within the specified bounding box.
 *
 * @throws IllegalArgumentException
 *   if any required parameters are missing or the stack cannot be found.
 *
 * @throws ObjectNotFoundException
 *    if the stack cannot be found.
 */
public long getTileCount(final StackId stackId,
                         final Double x,
                         final Double y,
                         final Double z,
                         final Integer width,
                         final Integer height)
        throws IllegalArgumentException, ObjectNotFoundException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("x", x);
    MongoUtil.validateRequiredParameter("y", y);
    MongoUtil.validateRequiredParameter("z", z);
    MongoUtil.validateRequiredParameter("width", width);
    MongoUtil.validateRequiredParameter("height", height);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);

    final double lowerRightX = x + width;
    final double lowerRightY = y + height;
    final Document tileQuery = getIntersectsBoxQuery(z, x, y, lowerRightX, lowerRightY);

    final long count = tileCollection.count(tileQuery);

    if (count == 0) {
        throwExceptionIfStackIsMissing(stackId);
    }

    LOG.debug("getTileCount: found {} tile spec(s) for {}.find({})",
              count, MongoUtil.fullName(tileCollection), tileQuery.toJson());

    return count;
}
 
Example 6
Source File: MongoDBDataStore.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@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);
    String strLimit = String.valueOf(queryparmes.get(DataStoreProtocol.LIMIT));
    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);
    if (!StringHelper.isEmpty(strLimit) && countN > Long.parseLong(strLimit)) {
        countN = Long.parseLong(strLimit);
    }
    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 7
Source File: CleanProjectList.java    From repairnator with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String projectPath = args[0];
    String dbUrl = args[1];
    String dbName = args[2];
    String collectionName = args[3];
    String destList = args[4];

    List<String> allProjects = Files.readAllLines(new File(projectPath).toPath());
    MongoConnection mongoConnection = new MongoConnection(dbUrl, dbName);
    MongoDatabase database = mongoConnection.getMongoDatabase();
    MongoCollection collection = database.getCollection(collectionName);

    List<String> selectedProjects = new ArrayList<>();
    for (String project : allProjects) {
        Repository repo = RepositoryHelper.getRepositoryFromSlug(project);
        if (repo != null) {
            Build b = repo.getLastBuild(false);
            if (b != null) {
                if (b.getBuildTool() == BuildTool.MAVEN) {
                    long results = collection.count(and(
                            eq("repositoryName", project),
                            ne("typeOfFailures", null)
                    ));

                    if (results > 0) {
                        selectedProjects.add(project);
                    }
                }
            }
        }
    }

    File outputFile = new File(destList);
    BufferedWriter buffer = new BufferedWriter(new FileWriter(outputFile));
    buffer.write(StringUtils.join(selectedProjects,"\n"));
    buffer.close();

    System.out.println("Read projects: "+allProjects.size()+" | Selected projects : "+selectedProjects.size());
    System.out.println(StringUtils.join(selectedProjects, "\n"));
}
 
Example 8
Source File: MongoCollectionCount.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase	db	= getMongoDatabase( _session, argStruct );
	
	String collection	= getNamedStringParam(argStruct, "collection", null);
	if ( collection == null )
		throwException(_session, "please specify a collection");
	
	cfData	queryData	= getNamedParam(argStruct, "query", null );
	
	try{
		Document qry = null;
		int count = 0;
		long start = System.currentTimeMillis();
		MongoCollection<Document> col = db.getCollection(collection);
		
		if ( queryData != null ){
			qry  	= getDocument(queryData);
			count	= (int)col.count( qry ); 
		}else
			count = (int)col.count();
		
		_session.getDebugRecorder().execMongo(col, "count", qry, System.currentTimeMillis()-start);

		return new cfNumberData( count );

	} catch (MongoException me){
		throwException(_session, me.getMessage());
		return null;
	}
}
 
Example 9
Source File: IdentifyInteractions.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Read patterns from mongo.
 *
 * @return the list
 */
private List<PatternReference> readPatternsFromMongo() {
  // TODO: Ideally this would do something in a more streaming manner, as there are likely to
  // be lots of examples. Loading all patterns into memory might be prohibitive.

  final MongoCollection<Document> collection = mongo.getDB().getCollection(patternCollection);

  final List<PatternReference> patterns = new ArrayList<>((int) collection.count());

  for (Document doc : collection.find()) {
    @SuppressWarnings("unchecked")
    List<Document> list = doc.get("words", List.class);

    final List<Word> tokens =
        list.stream()
            .map(
                l -> {
                  final String pos = l.getString("pos");
                  String lemma = l.getString("lemma");

                  // Fall back to actual text if no lemma
                  if (lemma == null) {
                    lemma = l.getString("text");
                  }

                  return new Word(lemma.trim().toLowerCase(), WordNetUtils.toPos(pos));
                })
            .filter(w -> w.getPos() != null)
            .collect(Collectors.toList());

    final PatternReference pattern = new PatternReference(doc.get("_id").toString(), tokens);
    pattern.setSourceType(((Document) doc.get("source")).getString("type"));
    pattern.setTargetType(((Document) doc.get("target")).getString("type"));
    patterns.add(pattern);
  }

  return patterns;
}
 
Example 10
Source File: DBMongoImpl.java    From heimdall with Apache License 2.0 4 votes vote down vote up
@Override
  public <T> Page<T> find(MongoCollection<Document> collection, Class<T> classType, Bson filters, Integer page, Integer limit) {

       page = page == null ? PAGE : page;
       limit = limit == null || limit > LIMIT ? LIMIT : limit;
       FindIterable<Document> documents;

       if (page > 0 && limit > 0) {

            if (filters != null) {

                 documents = collection.find(Filters.and(filters)).limit(limit).skip(page * limit);
            } else {

                 documents = collection.find().limit(limit).skip(page * limit);
            }
       } else if (page == 0 && limit > 0) {

            if (filters == null) {

                 documents = collection.find().limit(limit);
            } else {

                 documents = collection.find(Filters.and(filters)).limit(limit);
            }
       } else if (limit > 0) {

            if (filters == null) {

                 documents = collection.find().limit(limit);
            } else {

                 documents = collection.find(Filters.and(filters)).limit(limit);
            }
       } else {

            if (filters != null) {

                 documents = collection.find(Filters.and(filters)).limit(LIMIT);
            } else {

                 documents = collection.find().limit(LIMIT);
            }
       }

       Long totalElements = collection.count();

       List<T> list = new ArrayList<>();
       for (Document document : documents) {
         T parse;
try {
	parse = new ObjectMapper().readValue(document.toJson(), classType);
} catch (IOException e) {
	log.error("Json Parser error", e);
	parse = null;
}
            list.add(parse);
       }

       return buildPage(list, page, limit, totalElements);
  }
 
Example 11
Source File: RenderDao.java    From render with GNU General Public License v2.0 4 votes vote down vote up
private void deriveSectionData(final StackId stackId)
        throws IllegalArgumentException {

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final String sectionCollectionName = stackId.getSectionCollectionName();

    // db.<stack_prefix>__tile.aggregate(
    //     [
    //         { "$group": { "_id": { "sectionId": "$layout.sectionId", "z": "$z" } },
    //                       "tileCount": { "$sum": 1 },
    //                       "minX": { "$min": "$minX" }, "maxX": { "$max": "$maxX" },
    //                       "minY": { "$min": "$minY" }, "maxY": { "$max": "$maxY" }},
    //         { "$sort": { "_id.sectionId": 1 } }
    //     ]
    // )

    final Document idComponents = new Document("sectionId", "$layout.sectionId").append("z", "$z");
    final Document tileCountComponents = new Document("$sum", 1);
    final Document minXComponents = new Document("$min", "$minX");
    final Document maxXComponents = new Document("$max", "$maxX");
    final Document minYComponents = new Document("$min", "$minY");
    final Document maxYComponents = new Document("$max", "$maxY");
    final Document group = new Document(
            "_id", idComponents).append(
            "tileCount", tileCountComponents).append(
            "minX", minXComponents).append(
            "maxX", maxXComponents).append(
            "minY", minYComponents).append(
            "maxY", maxYComponents);

    final List<Document> pipeline = new ArrayList<>();
    pipeline.add(new Document("$group", group));
    pipeline.add(new Document("$sort", new Document("_id.sectionId", 1)));
    pipeline.add(new Document("$out", sectionCollectionName));

    if (LOG.isDebugEnabled()) {
        LOG.debug("deriveSectionData: running {}.aggregate({})",
                  MongoUtil.fullName(tileCollection),
                  MongoUtil.toJson(pipeline));
    }

    // mongodb java 3.0 driver notes:
    // -- need to retrieve first batch from cursor - via first() call - to force aggregate operation to run
    //    (even though we don't need to work with the batch result here)
    // -- need to set cursor batchSize to prevent NPE from cursor creation
    tileCollection.aggregate(pipeline).batchSize(0).first();

    if (! MongoUtil.exists(renderDatabase, sectionCollectionName)) {
        throw new IllegalStateException("Section data aggregation results were not saved to " +
                                        sectionCollectionName);
    }

    final MongoCollection<Document> sectionCollection = getSectionCollection(stackId);
    final long sectionCount = sectionCollection.count();

    LOG.debug("deriveSectionData: saved data for {} sections in {}",
              sectionCount, MongoUtil.fullName(sectionCollection));
}
 
Example 12
Source File: TestMongoClient.java    From jframe with Apache License 2.0 4 votes vote down vote up
public void testDriverStatus() {
		CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
				CodecRegistries.fromCodecs(new UuidCodec(
						UuidRepresentation.STANDARD)), MongoClient
						.getDefaultCodecRegistry());

		mongoClient.getDatabase("lech_rent").drop();
		MongoDatabase rent = mongoClient.getDatabase("lech_rent")
				.withCodecRegistry(codecRegistry);
		// rent.createCollection("driver_status", new CreateCollectionOptions()
		// .capped(true).sizeInBytes(0x100000));
		MongoCollection<Document> status = rent.getCollection("driver_status");
		status.deleteMany(Filters.eq("mobile", "18616020610"));
		if (status.count() == 0) {

		}
		status.createIndex(new Document("mobile", "text"));
		// status.createIndex(new Document("no", "text"));
		for (final Document index : status.listIndexes()) {
			System.out.println(index.toJson());
		}

		Document doc = new Document("loc",
				new Document("type", "Point").append("coordinates",
						Arrays.asList(-73.97, 40.77))).append("no", "dno")
				.append("usrImg", "/usr/driver.png")
				.append("mobile", "18616020610").append("status", 7)
				.append("car", new Document("no", "A00001"));
		status.insertOne(doc);
		// status.createIndex(keys);
		doc = status.find(Filters.eq("mobile", "18616020610")).first();

		System.out.println(doc.get("loc", Document.class).get("coordinates"));
		System.out.println(doc.get("loc", Document.class).get("coordinates",
				ArrayList.class));
		System.out.println(doc.get("car", Document.class));
		// System.out.println(doc.get("loc", Document.class));

//		UpdateResult updateResult = status.updateOne(Filters.eq("mobile",
//				"18616020610"), new Document("$set", new Document("car",
//				new Document("no", "A00002"))));
		doc = status.find(Filters.eq("mobile", "18616020610")).first();
		System.out.println(doc.get("car", Document.class));

		// updateResult = status.updateMany(Filters.lt("i", 100), new Document(
		// "$inc", new Document("i", 100)));
		// System.out.println(updateResult.getModifiedCount());
		// DeleteResult deleteResult = status.deleteOne(Filters.eq("i", 110));
		// System.out.println(deleteResult.getDeletedCount());

		// 2. Ordered bulk operation - order is guarenteed
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))));

		// 2. Unordered bulk operation - no guarantee of order of operation
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))), new BulkWriteOptions()
		// .ordered(false));

	}
 
Example 13
Source File: DAO.java    From Babler with Apache License 2.0 4 votes vote down vote up
/**
 * Counts blog posts in language that hasn't been optimizd by PostExtractor
 * @param lang of posts
 * @return count
 */
public static long countNonOpimizedBlogPostsInLanguage(String lang) {
    MongoCollection collection = getCollectionForClass(BlogPost.class);
    return collection.count(and(exists("optimized", false), eq("languageCode", lang)));

}
 
Example 14
Source File: DBMockImpl.java    From heimdall with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Page<T> find(MongoCollection<Document> collection, Class<T> classType, Bson filters, Integer page, Integer limit) {

    page = page == null ? PAGE : page;
    limit = limit == null || limit > LIMIT ? LIMIT : limit;
    FindIterable<Document> documents;

    if (page > 0 && limit > 0) {

        if (Objeto.notBlank(filters)) {

            documents = collection.find(Filters.and(filters)).limit(limit).skip(page * limit);
        } else {

            documents = collection.find().limit(limit).skip(page * limit);
        }
    } else if (page == 0 && limit > 0) {

        if (Objeto.notBlank(filters)) {

            documents = collection.find().limit(limit);
        } else {

            documents = collection.find(Filters.and(filters)).limit(limit);
        }
    } else if (limit > 0) {

        if (Objeto.notBlank(filters)) {

            documents = collection.find().limit(limit);
        } else {

            documents = collection.find(Filters.and(filters)).limit(limit);
        }
    } else {

        if (Objeto.notBlank(filters)) {

            documents = collection.find(Filters.and(filters)).limit(LIMIT);
        } else {

            documents = collection.find().limit(LIMIT);
        }
    }

    Long totalElements = collection.count();

    List<T> list = new ArrayList<>();
    for (Document document : documents) {

        T parse = helper.json().parse(document.toJson(), classType);
        list.add(parse);
    }

    return buildPage(list, page, limit, totalElements);
}
 
Example 15
Source File: RemoteCSEDAO.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public int getCount() {

		MongoCollection<Document> collection = context.getDatabaseManager().getCollection(collectionName);
		long count = collection.count(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.REMOTE_CSE.Value()));
		return (int)count;
		
	}
 
Example 16
Source File: AEDAO.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public int getCount() {

		MongoCollection<Document> collection = context.getDatabaseManager().getCollection(collectionName);
		long count = collection.count(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.AE.Value()));
		return (int)count;
		
	}
 
Example 17
Source File: RemoteCSEDAO.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public int getCount() {

		MongoCollection<Document> collection = context.getDatabaseManager().getCollection(collectionName);
		long count = collection.count(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.REMOTE_CSE.Value()));
		return (int)count;
		
	}
 
Example 18
Source File: AEDAO.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public int getCount() {

		MongoCollection<Document> collection = context.getDatabaseManager().getCollection(collectionName);
		long count = collection.count(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.AE.Value()));
		return (int)count;
		
	}
 
Example 19
Source File: DAO.java    From Babler with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
}
 
Example 20
Source File: DAO.java    From Babler with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @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)));
}