Java Code Examples for com.mongodb.DB#createCollection()

The following examples show how to use com.mongodb.DB#createCollection() . 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: MongodbLocalServerIntegrationTest.java    From hadoop-mini-clusters with Apache License 2.0 7 votes vote down vote up
@Test
public void testMongodbLocalServer() throws Exception {
    MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());

    DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
    DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY),
            new BasicDBObject());
    
    col.save(new BasicDBObject("testDoc", new Date()));
    LOG.info("MONGODB: Number of items in collection: {}", col.count());
    assertEquals(1, col.count());
    
    DBCursor cursor = col.find();
    while(cursor.hasNext()) {
        LOG.info("MONGODB: Document output: {}", cursor.next());
    }
    cursor.close();
}
 
Example 2
Source File: Task.java    From android-kubernetes-blockchain with Apache License 2.0 5 votes vote down vote up
public static DBCollection getDBCollection(DB database, String collectionName) {
	if (!database.collectionExists(collectionName)) {
		BasicDBObject basicDBObject = new BasicDBObject();
		database.createCollection(collectionName, basicDBObject);
		if (!(collectionName.equals("users") || collectionName.equals("results"))) {
			BasicDBObject dbObject = new BasicDBObject();
			dbObject.append("id", "count");
			dbObject.append("value", 0);
			database.getCollection(collectionName).insert(dbObject);
		}

		System.out.println("Collection created successfully : " + collectionName);
	}
	return database.getCollection(collectionName);
}
 
Example 3
Source File: MongodbSourceApplicationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	DB db = mongo.getDB("test");
	DBCollection col = db.createCollection("testing", new BasicDBObject());
	col.save(new BasicDBObject("greeting", "hello"));
	col.save(new BasicDBObject("greeting", "hola"));
}
 
Example 4
Source File: BuguDao.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
private void initCollection(String collectionName){
    Entity entity = clazz.getAnnotation(Entity.class);
    DB db = BuguFramework.getInstance().getConnection(entity.connection()).getDB();
    DBCollection dbColl;
    //if capped
    if(entity.capped() && !db.collectionExists(collectionName)){
        DBObject options = new BasicDBObject("capped", true);
        long capSize = entity.capSize();
        if(capSize != Default.CAP_SIZE){
            options.put("size", capSize);
        }
        long capMax = entity.capMax();
        if(capMax != Default.CAP_MAX){
            options.put("max", capMax);
        }
        dbColl = db.createCollection(collectionName, options);
    }else{
        dbColl = db.getCollection(collectionName);
    }
    setCollection(dbColl);
    
    //for @EnsureIndex
    EnsureIndex ei = clazz.getAnnotation(EnsureIndex.class);
    if(ei != null){
         if(! indexedSet.contains(collectionName)){
            synchronized (this) {
                if(! indexedSet.contains(collectionName)){
                    List<DBIndex> list = IndexUtil.getDBIndex(ei.value());
                    for(DBIndex dbi : list){
                        getCollection().createIndex(dbi.indexKeys, dbi.indexOptions);
                    }
                    indexedSet.add(collectionName);
                }
            }
        }
    }
}
 
Example 5
Source File: MongoDataLoadRule.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null
                || SetupConfig.get().getInjector() == null
                || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json")) continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance().getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}
 
Example 6
Source File: MongoExample.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB database = mongoClient.getDB("myMongoDb");

        // print existing databases
        mongoClient.getDatabaseNames().forEach(System.out::println);

        database.createCollection("customers", null);

        // print all collections in customers database
        database.getCollectionNames().forEach(System.out::println);

        // create data
        DBCollection collection = database.getCollection("customers");
        BasicDBObject document = new BasicDBObject();
        document.put("name", "Shubham");
        document.put("company", "Baeldung");
        collection.insert(document);

        // update data
        BasicDBObject query = new BasicDBObject();
        query.put("name", "Shubham");
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "John");
        BasicDBObject updateObject = new BasicDBObject();
        updateObject.put("$set", newDocument);
        collection.update(query, updateObject);

        // read data
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "John");
        DBCursor cursor = collection.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

        // delete data
        BasicDBObject deleteQuery = new BasicDBObject();
        deleteQuery.put("name", "John");
        collection.remove(deleteQuery);
    }