下面列出了com.mongodb.DB#createCollection ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
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);
}
@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"));
}
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);
}
}
}
}
}
@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();
}
}
};
}
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);
}