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

The following examples show how to use com.mongodb.client.MongoCollection#drop() . 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: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonNull() {
    MongoCollection<TestEntity> collection = db.getCollection("test_nonnull", TestEntity.class);
    collection.drop();

    TestEntity entity = new TestEntity();
    entity.setChecked(true);
    entity.setName(null);
    entity.setI(2);
    entity.setJ(null);

    collection.insertOne(entity);

    TestEntity returned = collection.find().first();
    Assert.assertEquals(entity.isChecked(), returned.isChecked());
    Assert.assertNull(returned.getName());
    Assert.assertEquals(entity.getI(), returned.getI());
    Assert.assertNull(returned.getJ());

    MongoCollection<Document> documentCollection = db.getCollection("test_nonnull", Document.class);
    Document document = documentCollection.find().first();
    Assert.assertTrue(document.containsKey("name"));
    Assert.assertTrue(document.containsKey("i"));
    Assert.assertFalse(document.containsKey("j"));
}
 
Example 2
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testReferenceMapping() {
    MongoCollection<TestEntityRef> collection = db.getCollection("test_ref", TestEntityRef.class);
    collection.drop();

    TestEntityRef entityRef = new TestEntityRef();
    entityRef.setName("ref");

    TestEntity entity = new TestEntity();
    entity.setName("bla");
    entityRef.setTestEntity(entity);

    collection.insertOne(entityRef);

    TestEntityRef returned = collection.find().first();
    Assert.assertEquals(entityRef.getName(), returned.getName());
    Assert.assertEquals(entityRef.getTestEntity().getName(), returned.getTestEntity().getName());
    Assert.assertEquals(entityRef.getTestEntity().isChecked(), returned.getTestEntity().isChecked());
    Assert.assertEquals(entityRef.getTestEntity().getI(), returned.getTestEntity().getI());
}
 
Example 3
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicMapping() {
    MongoCollection<TestEntity> collection = db.getCollection("test", TestEntity.class);
    collection.drop();

    TestEntity entity = new TestEntity();
    entity.setChecked(true);
    entity.setName("name");
    entity.setI(2);
    entity.setJ(1);

    collection.insertOne(entity);

    TestEntity returned = collection.find().first();
    Assert.assertEquals(entity.isChecked(), returned.isChecked());
    Assert.assertEquals(entity.getName(), returned.getName());
    Assert.assertEquals(entity.getI(), returned.getI());
    Assert.assertEquals(entity.getJ(), returned.getJ());
}
 
Example 4
Source File: QueryConverterIT.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteQuery() throws ParseException {
    String collection = "new_collection";
    MongoCollection newCollection = mongoDatabase.getCollection(collection);
    try {
        newCollection.insertOne(new Document("_id", "1").append("key", "value"));
        newCollection.insertOne(new Document("_id", "2").append("key", "value"));
        newCollection.insertOne(new Document("_id", "3").append("key", "value"));
        newCollection.insertOne(new Document("_id", "4").append("key2", "value2"));
        assertEquals(3, newCollection.count(new BsonDocument("key", new BsonString("value"))));
        QueryConverter queryConverter = new QueryConverter.Builder().sqlString("delete from " + collection + " where key = 'value'").build();
        long deleteCount = queryConverter.run(mongoDatabase);
        assertEquals(3, deleteCount);
        assertEquals(1, newCollection.countDocuments());
    } finally {
        newCollection.drop();
    }
}
 
Example 5
Source File: FiltersTest.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Test
public void testBitsAllClear() {
    MongoCollection<Document> collection = getDatabase().getCollection("users");
    collection.drop();

    collection.insertMany(asList(
        new Document("a", 54).append("binaryValueofA", "00110110").append("_t", "User"),
        new Document("a", 20).append("binaryValueofA", "00010100").append("_t", "User"),
        new Document("a", 20.0).append("binaryValueofA", "00010100").append("_t", "User")));

    FindOptions options = new FindOptions().logQuery();

    List<User> found = getDs().find(User.class)
                              .disableValidation()
                              .filter(bitsAllClear("a", 35)).iterator(options)
                              .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 2, found.size());

    found = getDs().find(User.class)
                   .disableValidation()
                   .filter(bitsAllClear("a", new int[]{1, 5})).iterator(options)
                   .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 2, found.size());
}
 
Example 6
Source File: MongoMapperCustomCodecIT.java    From mongo-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomCodec() throws Exception {
    MongoCollection<TestEntityCustomCodec> collection = db.getCollection("test_customcodec", TestEntityCustomCodec.class);
    collection.drop();

    TestEntityCustomCodec entity = new TestEntityCustomCodec();
    entity.setCustomCodecField(new CustomCodecField("a/b"));
    Assert.assertEquals("a", entity.getCustomCodecField().getPart1());
    Assert.assertEquals("b", entity.getCustomCodecField().getPart2());

    collection.insertOne(entity);

    TestEntityCustomCodec returned = collection.find().first();
    Assert.assertEquals("a", returned.getCustomCodecField().getPart1());
    Assert.assertEquals("b", returned.getCustomCodecField().getPart2());
}
 
Example 7
Source File: MongoSourceConnectorTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Ensure source can survive a restart with a drop")
void testSourceSurvivesARestartWithDrop() {
  assumeTrue(isGreaterThanThreeDotSix());
  MongoCollection<Document> coll = getDatabaseWithPostfix().getCollection("coll");

  Properties sourceProperties = new Properties();
  sourceProperties.put(MongoSourceConfig.DATABASE_CONFIG, coll.getNamespace().getDatabaseName());
  sourceProperties.put(
      MongoSourceConfig.COLLECTION_CONFIG, coll.getNamespace().getCollectionName());
  addSourceConnector(sourceProperties);

  insertMany(rangeClosed(1, 50), coll);
  assertProduced(createInserts(1, 50), coll);

  coll.drop();
  assertProduced(concat(createInserts(1, 50), singletonList(createDropCollection())), coll);

  restartSourceConnector(sourceProperties);
  insertMany(rangeClosed(51, 100), coll);

  assertProduced(
      concat(createInserts(1, 50), singletonList(createDropCollection()), createInserts(51, 100)),
      coll);
}
 
Example 8
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoreFields() throws Exception {
    MongoCollection<TestEntity> collection = db.getCollection("test_morefields", TestEntity.class);
    collection.drop();

    TestEntity entity = new TestEntity();
    entity.setName("a");
    entity.setChecked(true);
    entity.setJ(2);
    collection.insertOne(entity);

    MongoCollection<TestEntityRef> collection2 = db.getCollection("test_morefields", TestEntityRef.class);
    TestEntityRef returned = collection2.find().first();

    Assert.assertEquals(entity.getName(), returned.getName());
    Assert.assertEquals(entity.getId(), returned.getId());
}
 
Example 9
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransient() {
    MongoCollection<TestEntityTransient> collection = db.getCollection("test_array", TestEntityTransient.class);
    collection.drop();

    TestEntityTransient entity = new TestEntityTransient();
    entity.setNope("ahoj");

    collection.insertOne(entity);

    TestEntityTransient returned = collection.find().first();
    Assert.assertNull(returned.getNope());

}
 
Example 10
Source File: ZipsAggregationLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupTests() throws Exception {
    client = new MongoClient();
    MongoDatabase testDB = client.getDatabase("test");
    MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
    zipsCollection.drop();

    InputStream zipsJsonStream = ZipsAggregationLiveTest.class.getResourceAsStream("/zips.json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(zipsJsonStream));
    reader.lines()
      .forEach(line -> zipsCollection.insertOne(Document.parse(line)));
    reader.close();
}
 
Example 11
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 12
Source File: LoadBooks.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase library = client.getDatabase("library");
    MongoCollection books = library.getCollection("books");
    
    books.drop();
    library.createCollection("books");
    load(books);
}
 
Example 13
Source File: LoadAuthors.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase library = client.getDatabase("library");
    MongoCollection authors = library.getCollection("authors");
    
    authors.drop();
    library.createCollection("authors");
    load(authors);
}
 
Example 14
Source File: FiltersTest.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void testBitsAnySet() {
    MongoCollection<Document> collection = getDatabase().getCollection("users");
    collection.drop();

    collection.insertMany(asList(
        new Document("a", 54).append("binaryValueofA", "00110110").append("_t", "User"),
        new Document("a", 20).append("binaryValueofA", "00010100").append("_t", "User"),
        new Document("a", 20.0).append("binaryValueofA", "00010100").append("_t", "User")));

    FindOptions options = new FindOptions().logQuery();

    List<User> found = getDs().find(User.class)
                              .disableValidation()
                              .filter(bitsAnySet("a", 35)).iterator(options)
                              .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 1, found.size());

    options = new FindOptions().logQuery();
    found = getDs().find(User.class)
                   .disableValidation()
                   .filter(bitsAnySet("a", new int[]{1, 5})).iterator(options)
                   .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 1, found.size());
}
 
Example 15
Source File: FiltersTest.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void testBitsAllSet() {
    MongoCollection<Document> collection = getDatabase().getCollection("users");
    collection.drop();

    collection.insertMany(asList(
        new Document("a", 54).append("binaryValueofA", "00110110").append("_t", "User"),
        new Document("a", 20).append("binaryValueofA", "00010100").append("_t", "User"),
        new Document("a", 20.0).append("binaryValueofA", "00010100").append("_t", "User")));

    FindOptions options = new FindOptions().logQuery();

    List<User> found = getDs().find(User.class)
                              .disableValidation()
                              .filter(bitsAllSet("a", 50)).iterator(options)
                              .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 1, found.size());

    options = new FindOptions().logQuery();
    found = getDs().find(User.class)
                   .disableValidation()
                   .filter(bitsAllSet("a", new int[]{1, 5})).iterator(options)
                   .toList();

    Assert.assertEquals(getDs().getLoggedQuery(options), 1, found.size());
}
 
Example 16
Source File: TestAdvancedDatastore.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void testBulkInsert() {

    MongoCollection collection = getMapper().getCollection(TestEntity.class);
    this.getDs().insert(asList(new TestEntity(), new TestEntity(), new TestEntity(), new TestEntity(), new TestEntity()),
        new InsertManyOptions().writeConcern(WriteConcern.ACKNOWLEDGED));
    Assert.assertEquals(5, collection.countDocuments());

    collection.drop();
    this.getDs().insert(asList(new TestEntity(), new TestEntity(), new TestEntity(), new TestEntity(), new TestEntity()),
        new InsertManyOptions()
            .writeConcern(WriteConcern.ACKNOWLEDGED));
    Assert.assertEquals(5, collection.countDocuments());
}
 
Example 17
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullEnum() throws Exception {
    MongoCollection<TestEntityEnum> collection = db.getCollection("test_enum2", TestEntityEnum.class);
    collection.drop();

    TestEntityEnum entityEnum = new TestEntityEnum();
    entityEnum.setType(null);

    collection.insertOne(entityEnum);

    TestEntityEnum returned = collection.find().first();
    Assert.assertNull(returned.getType());
}
 
Example 18
Source File: MongoMapperIT.java    From mongo-mapper with Apache License 2.0 5 votes vote down vote up
@Test
public void testOtherCodec() {
    MongoCollection<TestEntityBigDecimal> collection = db.getCollection("test_bigdecimal", TestEntityBigDecimal.class);
    collection.drop();

    TestEntityBigDecimal entity = new TestEntityBigDecimal();
    entity.setBigNumber(new BigDecimal("0.0100000000000000000000000001"));

    collection.insertOne(entity);

    TestEntityBigDecimal returned = collection.find().first();
    Assert.assertEquals(entity.getBigNumber(), returned.getBigNumber());
}
 
Example 19
Source File: TestQuery.java    From morphia with Apache License 2.0 4 votes vote down vote up
private void dropProfileCollection() {
    MongoCollection<Document> profileCollection = getDatabase().getCollection("system.profile");
    profileCollection.drop();
}
 
Example 20
Source File: MongoUtil.java    From game-server with MIT License 4 votes vote down vote up
/**
 * 插入配置数据 先删除,在插入
 *
 * @param filePath
 * @param sheetName
 * @param dbName
 */
public static String insertConfigData(MongoClient client, String filePath, String sheetName, String dbName) throws Exception {
    String retString = sheetName + "更新成功";
    Args.Four<List<String>, List<String>, List<String>, List<List<Object>>> excel = ExcelUtil.readExcel(filePath, sheetName);
    if (excel == null) {
        LOGGER.warn("{}--{}未找到数据", filePath, sheetName);
        return "内部错误";
    }
    List<Document> documents = new ArrayList<>();

    MongoDatabase database = getMongoDatabase(client, dbName);
    if (database == null) {
        LOGGER.warn("{}数据库不存在", dbName);
        return "检查配置数据库不存在";
    }

    MongoCollection<Document> collection = database.getCollection(sheetName);
    if (collection == null) {
        LOGGER.warn("{}数据库集合{}不存在", dbName, collection);
        return "表不存在";
    }
    int row = excel.d().size();     //数据行数
    int column = excel.a().size();  //字段列数
    try {
        for (int i = 0; i < row; i++) {
            Document document = new Document();
            List<Object> datas = excel.d().get(i);
            for (int j = 0; j < column; j++) {
                document.append(excel.a().get(j), datas.get(j));
            }
            documents.add(document);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.error("Excel表{}有空行,空列,请删除", sheetName);
        retString = sheetName + "表有空行,空列,请删除";
        return retString;
    }

    if (documents.size() < 1) {
        return sheetName + "数据为空";
    }
    collection.drop();
    collection.insertMany(documents);
    return retString;
}