技术开发 频道

Java Tutorial:Java操作MongoDB入门

  Creating An Index

  创建索引

  MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the "i" field :

  MongoDB支持索引,并且很容易添加。只需要指定索引的字段和排序(升序1,降序-1)。下面是创建i降序索引的例子:

coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

 

  Getting a List of Indexes on a Collection

  查询collection全部索引

  You can get a list of the indexes on a collection :

List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}

 

  and you should see something like

  打印如下:

{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} }

 

  Quick Tour of the Administrative Functions

  管理方法

  Getting A List of Databases

  查询所有数据库

  You can get a list of the available databases:

  打印出可用的数据库:

Mongo m = new Mongo();
for (String s : m.getDatabaseNames()) {
System.out.println(s);
}

 

  Dropping A Database

  删除数据库

  You can drop a database by name using the Mongo object:

  通过名称删除:

m.dropDatabase("my_new_db");
0
相关文章