如何使用SPRING数据在MongoDB中创建集合

时间:2015-10-06 14:36:02

标签: mongodb spring-data-mongodb

使用Spring-Data-Mongo访问我的mongo数据库上的CRUD操作。我执行以下行

db.getCollectionNames()

当我处于调试模式时,我可以看到db._collections属性有4个值(我插入的集合)。但是当我查询

db.getCollection("collectionName")

我收回零回合。这是为什么?我做的时候也是如此

mongoTemplate.createCollection("collectionName");

但我知道收藏确实存在,因为当我做

之类的事情时
{{1}}

我得到一个例外,说集合已经存在。任何人都可以解释我可能缺少的东西

2 个答案:

答案 0 :(得分:1)

MongoTemplate 提供了一些管理集合的方法。以下示例演示了一些方法:

DBCollection collection = null;
if (!mongoTemplate.getCollectionNames().contains("collectionName")) {
    collection = mongoTemplate.createCollection("collectionName");
}

mongoTemplate.dropCollection("collectionName"); 

在上文中, getCollectionNames() 会返回一组集合名称, dropCollection() 会删除该集合。

答案 1 :(得分:0)

使用com.mongodb.client和com.mongodb包的MongoClient,MongoDatabase和MongoIterable。

MongoClient client = MongoClient(<host>, port);
MongoDatabase db = client.getDatabase(<Name of the database>);
MongoIterable<String> = db.listCollectionNames();

现在你可以遍历集合的所有名称。

此外,您甚至可以使用MongoCollection类从指定的集合中获取Document。如果不存在,getCollection()将创建集合。

MongoCollection<Document> collection = db.getCollection(<Collection name>);