分享

创建索引

 CevenCheng 2011-07-11

索引能提高检索数据的速度,你可以想像成在MySQL中创建索引一样,同样索引也是用B-Tree也实现的。
创建schedule的collection:
// 实例化Mongo对象,连接27017端口
Mongo mongo = new Mongo("localhost", 27017);
// 连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
DB db = mongo.getDB("test");
//得到要查询数据的 Collction, 如果没有就创建
DBCollection coll = db.getCollection("schedule");

Getting a List of Indexes on a Collection

List<DBObject> indexList = coll.getIndexInfo();  
for (DBObject o : indexList) {  
        System.out.println("index ---------" + o);  
}

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降序索引的例子:

1coll.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 :

 

1List<DBObject> list = coll.getIndexInfo();
2 
3 
4 
5for (DBObject o : list) {
6 
7    System.out.println(o);
8 
9}
 

and you should see something like

打印如下

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


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多