Java Code Examples for com.mongodb.client.MongoCollection

The following are top voted examples for showing how to use com.mongodb.client.MongoCollection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dooo   File: MongodbDataAccess.java   Source Code and License 10 votes vote down vote up
/**
 * 查询一个
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort
 * @return
 */
public Map<String, Object> findOne(
        String collectionName,
        MongodbQuery query, MongodbFields fields, MongodbSort sort) {
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find(query.getQuery());
    if (fields == null) {
        findIterable.projection(new MongodbFields().getDbObject());
    } else {
        findIterable.projection(fields.getDbObject());
    }
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    findIterable.limit(1);
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        if (cursor.hasNext()) {
            return cursor.next();
        }
    } finally {
        cursor.close();
    }
    return null;
}
 
Example 2
Project: mongodb-crud   File: UpdateDocumentsImpl.java   Source Code and License 9 votes vote down vote up
/**
 * This method update document with lastmodified properties 
 */
@Override
public void updateDocumentWithCurrentDate() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	Bson filter = null;
	Bson query = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		filter = eq("name", "Sundar");
		query = combine(set("age", 23), set("gender", "Male"),
				currentDate("lastModified"));
		UpdateResult result = collection.updateOne(filter, query);
		log.info("Update with date Status : " + result.wasAcknowledged());
		log.info("No of Record Modified : " + result.getModifiedCount());
	} catch (MongoException e) {
		log.error("Exception occurred while update Many Document with Date : " + e, e);
	}
}
 
Example 3
Project: mongodb-crud   File: DeleteDocumentsImpl.java   Source Code and License 8 votes vote down vote up
/**
 * This is deleted delete all document(s), which is matched
 */
@Override
public void deleteManyDocument() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	Bson query = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		query = lt("age", 20);
		DeleteResult result = collection.deleteMany(query);
		if (result.wasAcknowledged()) {
			log.info("Document deleted successfully \nNo of Document(s) Deleted : "
					+ result.getDeletedCount());
		}
	} catch (MongoException e) {
		log.error("Exception occurred while delete Many Document : " + e, e);
	}
}
 
Example 4
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   Source Code and License 7 votes vote down vote up
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

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

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

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

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

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
 
Example 5
Project: Jerkoff   File: MongoTest.java   Source Code and License 7 votes vote down vote up
@Test
@Ignore
public void testInsert() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("signature", "void test()");
        map.put("param", convert(new Object[0]));
        map.put("returnValue", 1);
        map.put("exception", convert(new IllegalAccessError("prova")));
        Document doc = new Document(map);
        coll.insertOne(doc);
        LOG.info(doc);
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
 
Example 6
Project: dooo   File: MongodbDataAccess.java   Source Code and License 7 votes vote down vote up
/**
 * 查询
 *
 * @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 7
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: UnorganizedTests.java   Source Code and License 7 votes vote down vote up
@Test
public void incrementMetadata() {
//This method is called from inside of getPlantByPlantId();
    boolean myPlant = plantController.
            incrementMetadata("58d1c36efb0cac4e15afd278", "pageViews");
    assertFalse(myPlant);
    boolean myPlant2 = plantController.incrementMetadata("16001.0","pageViews");
    assertTrue(myPlant2);


//This is necessary to test the data separately from getPlantByPlantId();
    Document searchDocument = new Document();
    searchDocument.append("id", "16001.0");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plantCollection = db.getCollection("plants");
    String before = JSON.serialize(plantCollection.find(searchDocument));
    plantController.incrementMetadata("16001.0","pageViews");
    String after = JSON.serialize(plantCollection.find(searchDocument));

    assertFalse(before.equals(after));
}
 
Example 8
Project: grain   File: MongodbManager.java   Source Code and License 7 votes vote down vote up
/**
 * 删除记录
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            记录
 * @return
 */
public static boolean deleteById(String collectionName, MongoObj mongoObj) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
		DeleteResult result = collection.deleteOne(filter);
		if (result.getDeletedCount() == 1) {
			return true;
		} else {
			return false;
		}
	} catch (Exception e) {
		if (log != null) {
			log.error("删除记录失败", e);
		}
		return false;
	}

}
 
Example 9
Project: Smart_City   File: ReportDAO.java   Source Code and License 7 votes vote down vote up
/**
 * Inserts a new report to the DB
 * 
 * @param report contains all data for insertion
 */
public static void insertReport(Report report) {
    Document newDocument = new Document();
    newDocument.append("priority", report.getPriority())
            .append("comment", report.getComment())
            .append("resolved", report.isResolved())
            .append("city_item_id", report.getCityItemId());

    if (report.getReportDate() != null) {
        newDocument.append("report_date", report.getReportDate().getTime());
    }
    if (report.getResolveDate() != null) {
        newDocument.append("resolve_date", report.getResolveDate().getTime());
    }

    MongoDatabase db = Configurator.INSTANCE.getDatabase();
    MongoCollection collection = db.getCollection(COLLECTION);
    collection.insertOne(newDocument); //TODO check if succeeds
}
 
Example 10
Project: polymorphia   File: UpdateTest.java   Source Code and License 7 votes vote down vote up
@Test
public void updatePojoTest() {

    Bson update = combine(set("user", "Jim"),
            set("action", Action.DELETE),
            // unfortunately at this point we need to provide a non generic class, so the codec is able to determine all types
            // remember: type erasure makes it impossible to retrieve type argument values at runtime
            // @todo provide a mechanism to generate non-generic class on the fly. Is that even possible ?
            // set("listOfPolymorphicTypes", buildNonGenericClassOnTheFly(Arrays.asList(new A(123), new B(456f)), List.class, Type.class),
            set("listOfPolymorphicTypes", new PolymorphicTypeList(Arrays.asList(new A(123), new B(456f)))),
            currentDate("creationDate"),
            currentTimestamp("_id"));

    FindOneAndUpdateOptions findOptions = new FindOneAndUpdateOptions();
    findOptions.upsert(true);
    findOptions.returnDocument(ReturnDocument.AFTER);

    MongoCollection<Pojo> pojoMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Pojo.class);

    Pojo pojo = pojoMongoCollection.findOneAndUpdate(Filters.and(Filters.lt(DBCollection.ID_FIELD_NAME, 0),
            Filters.gt(DBCollection.ID_FIELD_NAME, 0)), update, findOptions);

    assertNotNull(pojo.id);
}
 
Example 11
Project: GitHub   File: Repositories.java   Source Code and License 6 votes vote down vote up
protected Repository(
    RepositorySetup configuration,
    String collectionName,
    Class<T> type) {

  this.configuration = checkNotNull(configuration, "configuration");
  checkNotNull(collectionName, "collectionName");
  checkNotNull(type, "type");

  final TypeAdapter<T> adapter = checkAdapter(configuration.gson.getAdapter(type), type);
  final MongoCollection<Document> collection = configuration.database.getCollection(collectionName);
  // combine default and immutables codec registries
  final CodecRegistry registry = CodecRegistries.fromRegistries(collection.getCodecRegistry(), BsonEncoding.registryFor(type, adapter));

  this.collection = collection
      .withCodecRegistry(registry)
      .withDocumentClass(type);
}
 
Example 12
Project: digital-display-garden-iteration-4-dorfner-v2   File: FlowerRating.java   Source Code and License 6 votes vote down vote up
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "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 13
Project: Smart_City   File: CityItemDAO.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param cityItem Wrapper object for JSON values
 * @return id of inserted document
 */
public static String insertCityItem(CityItem cityItem)
{
    ObjectId id = new ObjectId();
    Document post = new Document();
    post.put("_id",id);
    post.put("type", Integer.toString(cityItem.getType()));
    post.put("location",new Document("x",String.valueOf(cityItem.getLongitude()))
            .append("y",String.valueOf(cityItem.getLatitude())));
    post.put("description", cityItem.getDescription());
    MongoCollection<Document> collection = Configurator.INSTANCE.getDatabase().getCollection(COLLECTION);
    try {
        collection.insertOne(post);
        return id.toString();
    } catch (DuplicateKeyException e) {
        e.printStackTrace();
        return "-1";
    }
}
 
Example 14
Project: nectar-server   File: FTSController.java   Source Code and License 6 votes vote down vote up
private static void buildChecksumDir(File dir, boolean isPublic, MongoCollection<Document> index) throws IOException {
    File[] contents = dir.listFiles();
    if(contents == null) return;

    List<Document> toInsert = new CopyOnWriteArrayList<>();

    for(File file : contents) {
        if(file.isDirectory()) {
            // Recursion: build for all in that directory
            buildChecksumDir(file, isPublic, index);
        } else {
            NectarServerApplication.getThreadPoolTaskExecutor().submit(() -> {
                try {
                    buildChecksumFile(file, index, toInsert, isPublic);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    if(!toInsert.isEmpty()) {
        index.insertMany(toInsert);
    }
}
 
Example 15
Project: uavstack   File: MongoDBDataStore.java   Source Code and License 6 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);
    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 16
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: FlowerRating.java   Source Code and License 6 votes vote down vote up
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"16001.0\"}";

    assertTrue(plantController.addFlowerRating(json, "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 17
Project: athena   File: ReplicateDatabaseData.java   Source Code and License 6 votes vote down vote up
public HashMap<String, MongoCollection> getCollectionList(MongoDatabase mongoDatabase) {
    HashMap<String, MongoCollection> dbCollectionList = new HashMap<String, MongoCollection>();
    String[] tableNameList = {athenaFeatureField.ERROR_MSG, athenaFeatureField.FLOW_REMOVED, athenaFeatureField.PACKET_IN,
            athenaFeatureField.PORT_STATUS, athenaFeatureField.FLOW_STATS, athenaFeatureField.QUEUE_STATS,
            athenaFeatureField.AGGREGATE_STATS, athenaFeatureField.TABLE_STATS, athenaFeatureField.PORT_STATS, "terabyte"};
    String teraBytes = "terabyte";

    for (String tableName : tableNameList) {
        MongoCollection dbCollection = mongoDatabase.getCollection(tableName);
        if (dbCollection == null) {
            mongoDatabase.createCollection(tableName);
            dbCollection = mongoDatabase.getCollection(tableName);
        }
        dbCollectionList.put(tableName, dbCollection);
    }

    return dbCollectionList;
}
 
Example 18
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: TestBedController.java   Source Code and License 6 votes vote down vote up
@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 19
Project: Jerkoff   File: MongoDBDaoImpl.java   Source Code and License 6 votes vote down vote up
@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 20
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: FlowerRating.java   Source Code and License 6 votes vote down vote up
@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 21
Project: mongodb-rdbms-sync   File: MngToOrclReader.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
	System.out.println("Reader started");
	MongoCollection<Document> collection = DBCacheManager.INSTANCE.getCachedMongoPool(mongoDbName, mongoUserName)
			.getDatabase(mongoDbName).getCollection(collectionName);
	FindIterable<Document> it = collection.find().batchSize(batchSize);
	it.forEach(new Block<Document>() {
		@Override
		public void apply(Document t) {
			System.out.println("Document read " + t);
			try {
				dataBuffer.put(t);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	});
}
 
Example 22
Project: config   File: MongoConfigRepository.java   Source Code and License 6 votes vote down vote up
@Override
public List<KeyValueConfigEntity> findAll(@Nonnull KeyValueConfigName configName) throws Exception {
  Objects.requireNonNull(configName);

  String collectionName = configName.getQualifiedName();
  MongoCollection<RawBsonDocument> collection =
      connector.getDatabase().getCollection(collectionName, RawBsonDocument.class);

  MongoCursor<RawBsonDocument> it = collection.find().iterator();
  if (!it.hasNext()) {
    return Collections.emptyList();
  }

  RawBsonDocument document = it.next();
  ByteArrayInputStream bin = new ByteArrayInputStream(document.getByteBuffer().array());
  ObjectMapper objectMapper = MongoConfigObjectMapper.getInstance();
  ObjectReader objectReader = objectMapper.readerFor(MongoConfigEntity.class);
  List<KeyValueConfigEntity> result = ((MongoConfigEntity) objectReader.readValue(bin)).getConfig();

  // set groupName on returned config key-value pairs
  return result.stream().map(input -> input.setConfigName(configName)).collect(Collectors.toList());
}
 
Example 23
Project: grain   File: MongodbManager.java   Source Code and License 6 votes vote down vote up
/**
 * 插入list
 * 
 * @param collectionName
 *            表名
 * @param list
 *            list
 * @return
 */
public static boolean insertMany(String collectionName, List<MongoObj> list) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		ArrayList<Document> documentList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			MongoObj mongoObj = list.get(i);
			Document document = objectToDocument(mongoObj);
			documentList.add(document);
		}
		collection.insertMany(documentList);
		return true;
	} catch (Exception e) {
		if (log != null) {
			log.error("插入documentList失败", e);
		}
		return false;
	}
}
 
Example 24
Project: nifi-nars   File: UpdateMongoIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testPushUpdate() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.media");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$addToSet");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify whether the update was made
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("insert_test");
        Document query = buildQuery("d.id", (JsonObject) JSON_PROVIDER.parse(contents));
        assertEquals(1, collection.count(query.append("d.media", new Document("$exists", true))));
    }
}
 
Example 25
Project: sagiri   File: Sagiri.java   Source Code and License 5 votes vote down vote up
public static MongoCollection getCollection(String suffix) {
    String className = Thread.currentThread().getStackTrace()[2].getClassName();

    for(PluginBubble bubble : getPlugins()) {
        String packageName = bubble.getPlugin().getClass().getPackage().getName();

        if(className.startsWith(packageName)) {
            return mongoDatabase.getCollection(
                    String.format("%s_%s", packageName, suffix)
            );
        }
    }

    return null;
}
 
Example 26
Project: grain   File: MongodbManager.java   Source Code and License 5 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 27
Project: mongodb-crud   File: QueryDocumentsImpl.java   Source Code and License 5 votes vote down vote up
/**
 * This method retrieve document(s) based on parameters
 * @param query - query have to execute
 * @param operator - this is for debug purpose
 */
private void getData(Bson query, String operator) {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> list = collection.find(query);
        for (Document doc : list) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException e) {
        log.error("exception occurred while getting Document using " + operator + " : " + e, e);
    }
}
 
Example 28
Project: mongodb-crud   File: UpdateDocumentsImpl.java   Source Code and License 5 votes vote down vote up
/**
 * This method update only one one document which is matched first
 */
@Override
public void updateOneDocument() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	Bson filter = null;
	Bson query = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		filter = eq("name", "Sundar");
		query = combine(set("age", 23), set("gender", "Male"));
		UpdateResult result = collection.updateOne(filter, query);
		log.info("UpdateOne Status : " + result.wasAcknowledged());
		log.info("No of Record Modified : " + result.getModifiedCount());
	} catch (MongoException e) {
		log.error("Exception occurred while update single Document : " + e, e);
	}
}
 
Example 29
Project: rocketmq-flink-plugin   File: MongoManager.java   Source Code and License 5 votes vote down vote up
/**
 * @param dbName         库名
 * @param collectionName 集合名
 * @param json1          条件
 * @param json2          保存doc
 * @return upsert结果信息
 */
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateOptions up = new UpdateOptions();
        up.upsert(true);
        UpdateResult ur = coll.updateOne(doc1, doc2, up);
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
 
Example 30
Project: intellead-integration-tests   File: Steps.java   Source Code and License 5 votes vote down vote up
@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 31
Project: twitter-stuff   File: StatusUtils.java   Source Code and License 5 votes vote down vote up
public static void saveFailureStatusProcesssed(MongoDatabase mongoDatabase, long id, boolean processed) {
    MongoCollection<Document> failureCollection = mongoDatabase.getCollection("failures");
    failureCollection.replaceOne(
            Filters.eq("tweet_id", id),
            new Document().append("tweet_id", id).append("processed", processed),
            new UpdateOptions().upsert(true));
}
 
Example 32
Project: mongodb-crud   File: InsertDocumentsImpl.java   Source Code and License 5 votes vote down vote up
/**
 * This method insert the more than one document at a time
 */
@Override
public void insertMultipleDocuments() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());

		Document journal = new Document("item", "journal")
				.append("qty", 25).append("tags", asList("blank", "red"));

		Document journalSize = new Document("h", 14).append("w", 21)
				.append("uom", "cm");
		journal.put("size", journalSize);

		Document mat = new Document("item", "mat").append("qty", 85)
				.append("tags", singletonList("gray"));

		Document matSize = new Document("h", 27.9).append("w", 35.5)
				.append("uom", "cm");
		mat.put("size", matSize);

		Document mousePad = new Document("item", "mousePad").append("qty",
				25).append("tags", asList("gel", "blue"));

		Document mousePadSize = new Document("h", 19).append("w", 22.85)
				.append("uom", "cm");
		mousePad.put("size", mousePadSize);
		collection.insertMany(asList(journal, mat, mousePad));
		log.info("Multiple Document Insert Successfully...");
	} catch (MongoException | ClassCastException e) {
		log.error("Exception occurred while insert **Multiple Document** : " + e, e);
	}
}
 
Example 33
Project: Mp3Bib   File: Database.java   Source Code and License 5 votes vote down vote up
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 34
Project: nectar-server   File: AuthController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(NectarServerApplication.ROOT_PATH + "/auth/removeClient")
public ResponseEntity removeClient(@RequestParam(value = "token") String jwtRaw, @RequestParam(value = "uuid") String uuid,
                                   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> clients = NectarServerApplication.getDb().getCollection("clients");

        Document client = clients.find(Filters.eq("uuid", uuid)).first();

        if(client == null) // Check if the client exists
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Client not found in database.");

        if(!(client.getOrDefault("loggedInUser", "null").equals("null"))) { // Check if a user is currently signed into the client.
            NectarServerApplication.getLogger().warn("Attempted client deletion from " + request.getRemoteAddr() + ", a user is already signed into client " + uuid);
            return ResponseEntity.status(HttpStatus.CONFLICT).body("A user is currently signed into this client.");
        }

        if(SessionController.getInstance().sessions.containsKey(uuid)) { // Check if the client is currently online with a session open
            SessionController.getInstance().sessions.remove(uuid); // Remove the session and it's token
            NectarServerApplication.getLogger().info("Revoked token for " + uuid + ": client deleted");
        }

        clients.deleteOne(Filters.eq("uuid", uuid)); // Delete client from the MongoDB database

        NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.NOTICE, "Deleted client " + uuid + ", traced from " + request.getRemoteAddr());
    } else {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Success.");
}
 
Example 35
Project: nectar-server   File: AuthController.java   Source Code and License 5 votes vote down vote up
protected static ResponseEntity checkUserAdmin(SessionToken token, MongoCollection<Document> users, Document doc) {
    // getString will throw an exception if the key is not present in the document
    String loggedInUser = doc.getString("loggedInUser");
    if(loggedInUser.equals("none")) {
        // No user is logged in
        throw new RuntimeException(); // Move to catch block
    }

    Document userDoc = users.find(Filters.eq("username", loggedInUser)).first();

    if(userDoc == null) { // We can't find the logged in user in the users database, strange
        NectarServerApplication.getLogger().warn("Failed to find logged in user \"" + loggedInUser + "\" for session "
                + token.getUuid() + " while processing user registration"
        );
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to find current logged in user in DB.");
    } else { // User found, check admin now
        if(!userDoc.getBoolean("admin", false)) {
            NectarServerApplication.getLogger().warn("ATTEMPTED CLIENT REGISTRATION BY NON_ADMIN USER \"" + loggedInUser + "\""
                    + " from session " + token.getUuid()
            );

            NectarServerApplication.getEventLog().addEntry(EventLog.EntryLevel.WARNING, "A non-admin user attempted to register a client from " + token.getUuid());
            throw new RuntimeException(); // Move to catch block
        }
        // User is confirmed logged in and admin, all checks passed.
    }
    return null;
}
 
Example 36
Project: rocketmq-flink-plugin   File: MongoManager.java   Source Code and License 5 votes vote down vote up
/**
 * @param dbName         库名
 * @param collectionName 表名
 * @param json1          条件
 * @param json2          保存doc
 * @return 更新结果信息
 */
public JSONObject executeUpdate(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateResult ur = coll.updateOne(doc1, doc2);
        System.out.println("doc1 = " + doc1.toString());
        System.out.println("doc2 = " + doc2.toString());
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
 
Example 37
Project: nectar-server   File: QueryController.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping(NectarServerApplication.ROOT_PATH + "/query/queryUsers")
public ResponseEntity queryUsers(@RequestParam(value = "token") String jwtRaw, HttpServletRequest request) {
    ManagementSessionToken token = ManagementSessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
    if(token == null)
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");

    if(!SessionController.getInstance().checkManagementToken(token)) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    JSONObject returnJSON = new JSONObject();

    MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
    MongoCollection<Document> users = NectarServerApplication.getDb().getCollection("users");
    users.find().forEach((Block<Document>) document -> {
        String username = document.getString("username");
        boolean admin = document.getBoolean("admin", false);

        JSONObject userJSON = new JSONObject();
        userJSON.put("admin", admin);

        Document clientDoc = clients.find(Filters.eq("loggedInUser", username)).first();
        if(clientDoc == null) {
            userJSON.put("signedIn", false);
        } else {
            userJSON.put("signedIn", true);
        }

        returnJSON.put(username, userJSON);
    });

    return ResponseEntity.ok(returnJSON.toJSONString());
}
 
Example 38
Project: dooo   File: SimpleMongodbAccessor.java   Source Code and License 5 votes vote down vote up
/**
 * 批量插入数据
 */
public void batchInsert(String collectionName, List<Map<String, Object>> list) {
    MongoCollection collection = mongoDatabase.getCollection(collectionName);
    List<Document> documents = new ArrayList<>();
    for (Map<String, Object> map : list) {
        documents.add(new Document(map));
    }
    collection.insertMany(documents);
}
 
Example 39
Project: nectar-server   File: ClientSession.java   Source Code and License 5 votes vote down vote up
public void updateState(ClientState state) {
    NectarServerApplication.getLogger().info("Client " + token.getUuid() + " state updated to: " + state.toString());
    this.state = state;

    MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
    clients.updateOne(Filters.eq("uuid", token.getUuid()),
            new Document("$set", new Document("state", state.toInt())));
}
 
Example 40
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: ExcelParser.java   Source Code and License 5 votes vote down vote up
public static void setLiveUploadId(String uploadID){

        MongoClient mongoClient = new MongoClient();
        MongoDatabase test = mongoClient.getDatabase("test");
        MongoCollection configCollection = test.getCollection("config");

        configCollection.deleteMany(exists("liveUploadId"));
        configCollection.insertOne(new Document().append("liveUploadId", uploadID));
    }
 
Example 41
Project: nifi-nars   File: UpdateMongoIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnsetUpdate() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.g");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$unset");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify whether the update was made
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("insert_test");
        Document query = buildQuery("d.id", (JsonObject) JSON_PROVIDER.parse(contents));
        assertEquals(collection.count(query.append("d.g", new Document("$exists", true))), 0);
    }
}
 
Example 42
Project: spring-multitenancy   File: MongoPersistentEntityIndexCreator.java   Source Code and License 5 votes vote down vote up
private Map<String, String> getCurrentIndex(MongoCollection<Document> collection){
	
	Map<String, String> result = new  HashMap<>();
	
	MongoCursor<Document> indexes = collection.listIndexes().iterator();
	
	while(indexes.hasNext()){
		Document index = indexes.next();
		Document definition = (Document)index.get("key");
		result.put(index.getString("name"), definition.toJson());
	}
	
	return result;
}
 
Example 43
Project: osm-processor   File: MongoStore.java   Source Code and License 5 votes vote down vote up
/**
 * Find Documents of a collection matching the passed filter, paginated.
 */
public List<Document> find(final String collectionName, final Document filter, int pageNo, int pageSize) {
    // Sanity checks
    if (StringUtils.isEmpty(collectionName)) {
        throw new IllegalArgumentException("find :: Collection name should not be blank");
    }

    final int skipCount = (pageNo - 1) * pageSize;

    // Collection
    MongoCollection<Document> collection = this.database.getCollection(collectionName);
    List<Document> result = collection.find(filter).skip(skipCount).limit(pageSize).into(new ArrayList<>());

    return result;
}
 
Example 44
Project: oplog-analyzer   File: OplogAnalyzer.java   Source Code and License 5 votes vote down vote up
public void process() {
    
    MongoDatabase db = mongoClient.getDatabase("local");
    MongoCollection<RawBsonDocument> oplog = db.getCollection("oplog.rs", RawBsonDocument.class);

    RawBsonDocument lastOplogEntry = oplog.find().sort(new Document("$natural", -1)).first();

    BsonTimestamp lastTimestamp = (BsonTimestamp) lastOplogEntry.get("ts");

    System.out.println(lastTimestamp);

    Document query = new Document("ts", new Document("$lt", lastTimestamp));
    for (RawBsonDocument doc : oplog.find(query).noCursorTimeout(true)) {
        
        BsonString ns = (BsonString) doc.get("ns");
        BsonString op = (BsonString) doc.get("op");

        // ignore no-op
        if (!op.getValue().equals("n")) {
            OplogEntryKey key = new OplogEntryKey(ns.getValue(), op.getValue());
            EntryAccumulator accum = accumulators.get(key);
            if (accum == null) {
                accum = new EntryAccumulator(key);
                accumulators.put(key, accum);
            }
            long len = doc.getByteBuffer().asNIO().array().length;
            accum.addExecution(len);
        }

        if (stop) {
            mongoClient.close();
            report();
            break;
        }
    }
}
 
Example 45
Project: pac4j-plus   File: MongoAuthenticator.java   Source Code and License 5 votes vote down vote up
@Override
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction {

    init(context);

    final String username = credentials.getUsername();

    final MongoDatabase db = mongoClient.getDatabase(usersDatabase);
    final MongoCollection<Document> collection = db.getCollection(usersCollection);
    final List<Document> users = new ArrayList<>();
    try (final MongoCursor<Document> cursor = collection.find(eq(usernameAttribute, username)).iterator()) {
        int i= 0;
        while (cursor.hasNext() && i <= 2) {
            users.add(cursor.next());
            i++;
        }
    }
    logger.debug("Fonund {} users for username: {}", users.size(), username);

    if (users.isEmpty()) {
        throw new AccountNotFoundException("No account found for: " + username);
    } else if (users.size() > 1) {
        throw new MultipleAccountsFoundException("Too many accounts found for: " + username);
    } else {
        final Map<String, Object> user = users.get(0);
        final String returnedPassword = (String) user.get(passwordAttribute);
        if (!getPasswordEncoder().matches(credentials.getPassword(), returnedPassword)) {
            throw new BadCredentialsException("Bad credentials for: " + username);
        } else {
            final MongoProfile profile = createProfile(username, attributes.split(","), user);
            credentials.setUserProfile(profile);
        }
    }
}
 
Example 46
Project: digital-display-garden-iteration-2-spraguesanborn   File: UserControllerSpec.java   Source Code and License 5 votes vote down vote up
@Before
public void clearAndPopulateDB() throws IOException {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("test");
    MongoCollection<Document> userDocuments = db.getCollection("users");
    userDocuments.drop();
    List<Document> testUsers = new ArrayList<>();
    testUsers.add(Document.parse("{\n" +
            "                    name: \"Chris\",\n" +
            "                    age: 25,\n" +
            "                    company: \"UMM\",\n" +
            "                    email: \"[email protected]\"\n" +
            "                }"));
    testUsers.add(Document.parse("{\n" +
            "                    name: \"Pat\",\n" +
            "                    age: 37,\n" +
            "                    company: \"IBM\",\n" +
            "                    email: \"[email protected]\"\n" +
            "                }"));
    testUsers.add(Document.parse("{\n" +
            "                    name: \"Jamie\",\n" +
            "                    age: 37,\n" +
            "                    company: \"Frogs, Inc.\",\n" +
            "                    email: \"[email protected]\"\n" +
            "                }"));
    ObjectId samsId = new ObjectId();
    BasicDBObject sam = new BasicDBObject("_id", samsId);
    sam = sam.append("name", "Sam")
            .append("age", 45)
            .append("company", "Frogs, Inc.")
            .append("email", "[email protected]");
    samsIdString = samsId.toHexString();
    userDocuments.insertMany(testUsers);
    userDocuments.insertOne(Document.parse(sam.toJson()));

    // It might be important to construct this _after_ the DB is set up
    // in case there are bits in the constructor that care about the state
    // of the database.
    userController = new UserController("test");
}
 
Example 47
Project: Babler   File: DAO.java   Source Code and License 5 votes vote down vote up
/**
 * Search the DB  for tweets in a specific language
  * @param language to search for
 * @return list of users with tweets in that language
 */
public static Set<String> getUsersWithTweetInLanguage(String language) {
    MongoCollection collection = getCollectionForClass(Tweet.class);
    Set<String> s = new HashSet<String>();
    //find users with tweets having language
    MongoCursor cursor = collection.find(and(eq("languageCode", language))).projection(include("url")).iterator();
    while(cursor.hasNext())
    {
        JSONObject obj = new JSONObject(cursor.next().toString());
        String url = obj.get("url").toString();
        String [] urlParts = url.split("/");
        s.add(urlParts[3]);
    }
    return s;
}
 
Example 48
Project: Babler   File: DAO.java   Source Code and License 5 votes vote down vote up
/**
 * returns a list of all twitter users in db
 * @return
 */
public static Set<String> getAllTwitterUserIds(){
    MongoCollection collection = getCollectionForClass(Tweet.class);
    Set<String> s = new HashSet<String>();
    MongoCursor cursor = collection.find().projection(include("url")).iterator();
    while(cursor.hasNext())
    {
        JSONObject obj = new JSONObject(cursor.next().toString());
        String url = obj.get("url").toString();
        String [] urlParts = url.split("/");
        s.add(urlParts[3]);
    }
    return s;

}
 
Example 49
Project: Babler   File: DAO.java   Source Code and License 5 votes vote down vote up
/**
 * deletes an entry from the DB
 * @param entry to delete
 */
public static void deleteEntry(DBEntry entry) {
    if(entry == null)
        return;

    MongoDatabase db = MongoDB.INSTANCE.getDatabase("scraping");
    String collectionName = getCollectionName(entry);

    MongoCollection collection = db.getCollection(collectionName, BasicDBObject.class);
    collection.deleteOne(eq("_id",entry.getId()));
}
 
Example 50
Project: Babler   File: DAO.java   Source Code and License 5 votes vote down vote up
/**
 * Checks if a document exists in the DB by url
 * @param c type of document
 * @param url to check for
 * @return true if not exists
 */
public static boolean isNewByURL(Class c, String url) {

    MongoCollection collection = getCollectionForClass(c);
    BasicDBObject obj = (BasicDBObject) collection.find(eq("url",url)).first();
    if(obj != null)
        return false;
    else
        return true;
}
 
Example 51
Project: nifi-nars   File: StoreInMongoIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testKeepIndexOutsideNamespace() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());
    addMongoService(runner);
    MongoCollection<Document> collection = mongo.getMongoClient().getDatabase(MONGO_DATABASE_NAME).getCollection("index_test");
    Document index = new Document().append("_id", "hashed");
    collection.createIndex(index);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "index_test");
    runner.assertValid();
    runner.run();
    Set<String> indexNames = AbstractMongoProcessor.getIndexNames(collection);
    String normalizedIndexName = AbstractMongoProcessor.normalizeIndexName("", index.toJson());
    assertTrue(indexNames.contains(normalizedIndexName));
}
 
Example 52
Project: digital-display-garden-iteration-4-revolverenguardia-1   File: TestBedController.java   Source Code and License 5 votes vote down vote up
@Test
public void TestIncrementBedData(){

    bedController.incrementBedMetadata("7.0","pageViews","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 bedPageViews =  (int)((Document) result.get("metadata")).get("pageViews");

    assertEquals("this bed should only have 1 pageView",1, bedPageViews);
}
 
Example 53
Project: QDrill   File: MongoGroupScan.java   Source Code and License 5 votes vote down vote up
@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 54
Project: osm-processor   File: MongoStore.java   Source Code and License 5 votes vote down vote up
/**
 * 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 55
Project: dooo   File: MongodbDataAccess.java   Source Code and License 5 votes vote down vote up
/**
 * 创建索引
 *
 * @param collectionName 集合
 * @param indexName      索引名
 * @param keys           键信息,如 securityCode:1
 * @param isUnique       是否唯一索引
 */
public void createIndex(String collectionName, String indexName, Map<String, Integer> keys, boolean isUnique) {
    MongoCollection collection = sMongoDatabase.getCollection(collectionName);
    IndexOptions indexOptions = new IndexOptions();
    indexOptions.background(true);
    indexOptions.unique(isUnique);
    indexOptions.name(indexName);
    Map<String, Object> keyIndexs = new HashMap<>(16);
    for (Map.Entry<String, Integer> entry : keys.entrySet()) {
        keyIndexs.put(entry.getKey(), entry.getValue() > 0 ? 1 : entry.getValue() == 0 ? 0 : -1);
    }
    collection.createIndex(new Document(keyIndexs), indexOptions);
}
 
Example 56
Project: dooo   File: MongodbDataAccess.java   Source Code and License 5 votes vote down vote up
/**
 * 查询
 *
 * @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 57
Project: spring-multitenancy   File: MongoBasicOperations.java   Source Code and License 5 votes vote down vote up
@Override
public <T> MongoCollection<Document> getCollection(String collectionName, Class<T> type) {
	MongoDatabase database = dataSource.getDataSource();
	
	MongoCollection<Document> collection = database.getCollection(collectionName);
	
	List<MongoIndexChange> indexChanges = index.getChanges(collection, type);
	
	for (MongoIndexChange change : indexChanges) {
		ensureIndex(collection, change.getName(), change.getDefinition(), change.getOptions(), change.isReplace());
	}	
	
	return database.getCollection(collectionName);
}
 
Example 58
Project: config   File: MongoConfigEventListener.java   Source Code and License 5 votes vote down vote up
private void insertOne(AuditLogEntity input) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
    ObjectMapper objectMapper = MongoConfigObjectMapper.getInstance();
    objectMapper.writer().writeValue(baos, input);
  } catch (Exception e) {
    LOGGER.error("Exception at converting obj: {} to bson, cause: {}", input, e);
    throw ThrowableUtil.propagate(e);
  }
  MongoCollection<RawBsonDocument> collection =
      connector.getDatabase().getCollection(collectionName, RawBsonDocument.class);
  collection.insertOne(new RawBsonDocument(baos.toByteArray()));
}
 
Example 59
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: TestExcelParser.java   Source Code and License 5 votes vote down vote up
@Test
public  void testSetLiveUploadID() {
     parser.setLiveUploadId("JAPSER");


     Document searchDocument = new Document();
     searchDocument.append("liveUploadId", "JAPSER");
     MongoClient mongoClient = new MongoClient();
     MongoDatabase test = mongoClient.getDatabase("test");
     MongoCollection configCollection = test.getCollection("config");
     String uploadID = JSON.serialize(configCollection.find(searchDocument));
     assertEquals(80,uploadID.length());
 }
 
Example 60
Project: intellead-integration-tests   File: Steps.java   Source Code and License 5 votes vote down vote up
@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);
}