java类com.mongodb.client.MongoCollection的实例源码

DeleteDocumentsImpl.java 文件源码 项目:mongodb-crud 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
UnorganizedTests.java 文件源码 项目:digital-display-garden-iteration-3-sixguysburgers-fries 阅读 29 收藏 0 点赞 0 评论 0
@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));
}
ReportDAO.java 文件源码 项目:Smart_City 阅读 22 收藏 0 点赞 0 评论 0
/**
 * 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
}
Repositories.java 文件源码 项目:GitHub 阅读 50 收藏 0 点赞 0 评论 0
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);
}
UpdateDocumentsImpl.java 文件源码 项目:mongodb-crud 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
FlowerRating.java 文件源码 项目:digital-display-garden-iteration-4-dorfner-v2 阅读 21 收藏 0 点赞 0 评论 0
@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);
}
TestPlantComment.java 文件源码 项目:digital-display-garden-iteration-4-dorfner-v2 阅读 30 收藏 0 点赞 0 评论 0
@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"));
  }
MongoTest.java 文件源码 项目:Jerkoff 阅读 28 收藏 0 点赞 0 评论 0
@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();
    }
}
CityItemDAO.java 文件源码 项目:Smart_City 阅读 18 收藏 0 点赞 0 评论 0
/**
 *
 * @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";
    }
}
FTSController.java 文件源码 项目:nectar-server 阅读 20 收藏 0 点赞 0 评论 0
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);
    }
}
MongoDBDataStore.java 文件源码 项目:uavstack 阅读 25 收藏 0 点赞 0 评论 0
@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;

}
FlowerRating.java 文件源码 项目:digital-display-garden-iteration-4-revolverenguardia-1 阅读 25 收藏 0 点赞 0 评论 0
@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"));
}
ReplicateDatabaseData.java 文件源码 项目:athena 阅读 29 收藏 0 点赞 0 评论 0
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;
}
MongodbDataAccess.java 文件源码 项目:dooo 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 查询
 *
 * @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;
}
TestBedController.java 文件源码 项目:digital-display-garden-iteration-4-revolverenguardia-1 阅读 21 收藏 0 点赞 0 评论 0
@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());

}
MongoDBDaoImpl.java 文件源码 项目:Jerkoff 阅读 20 收藏 0 点赞 0 评论 0
@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;
}
FlowerRating.java 文件源码 项目:digital-display-garden-iteration-3-sixguysburgers-fries 阅读 26 收藏 0 点赞 0 评论 0
@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"));
}
MongodbDataAccess.java 文件源码 项目:dooo 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 查询一个
 *
 * @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;
}
MngToOrclReader.java 文件源码 项目:mongodb-rdbms-sync 阅读 24 收藏 0 点赞 0 评论 0
@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();
            }
        }
    });
}
MongoConfigRepository.java 文件源码 项目:config 阅读 28 收藏 0 点赞 0 评论 0
@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());
}
MongodbManager.java 文件源码 项目:grain 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 插入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;
    }
}
MongodbManager.java 文件源码 项目:grain 阅读 27 收藏 0 点赞 0 评论 0
/**
 * 删除记录
 * 
 * @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;
    }

}
UpdateTest.java 文件源码 项目:polymorphia 阅读 33 收藏 0 点赞 0 评论 0
@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);
}
UpdateMongoIT.java 文件源码 项目:nifi-nars 阅读 26 收藏 0 点赞 0 评论 0
@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))));
    }
}
Sagiri.java 文件源码 项目:sagiri 阅读 20 收藏 0 点赞 0 评论 0
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;
}
MongodbManager.java 文件源码 项目:grain 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 获取个数
 * 
 * @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;
    }

}
QueryDocumentsImpl.java 文件源码 项目:mongodb-crud 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
UpdateDocumentsImpl.java 文件源码 项目:mongodb-crud 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
MongoManager.java 文件源码 项目:rocketmq-flink-plugin 阅读 25 收藏 0 点赞 0 评论 0
/**
 * @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;
}
Steps.java 文件源码 项目:intellead-integration-tests 阅读 21 收藏 0 点赞 0 评论 0
@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);
}


问题


面经


文章

微信
公众号

扫码关注公众号