mongodb的collection几个功能介绍

1.collection介绍

在mongodb中,collection相当于关系型数据库的表,但并不需提前创建,更不需要预先定义字段

db.collect1.save({username:'mayj',mail:'test@abc.com'})  #向collect1中插入一条记录,collection会在第一次插入记录的时候自动创建

db.collect1.save({username:'name2',mail:'name2@abc.com',age:28})  #插入一条新记录,相对上条记录这次有三个key,类似三个字段

db.collect1.find();  #列出collect1中的所有记录

 

2.对collection可以进行任意维度的查询

以上面的collect1为例,可以执行

> db.collect1.find({username:'mayj'})  #查询username='mayj'的记录,相当于执行select * from collect1 where username='mayj'

结果:{ "_id" : ObjectId("4cb7efb7a3f37347a20e37ea"), "username" : "mayj", "mail" : "test@abc.com" }

 

> db.collect1.find({age:28})  #查询age=28的记录,相当于select * from collect1 where age=28

{ "_id" : ObjectId("4cb7efb7a3f37347a20e37eb"), "username" : "name2", "mail" : "name2@abc.com", "age" : 28 }

 

> db.collect1.find({age:28},{username:true})  #查询age=28的username值, 相当于select username from collect1 where age=28

{ "_id" : ObjectId("4cb7efb7a3f37347a20e37eb"), "username" : "name2" }

 

其实还可以对collection里的任意key创建索引,以加快查询速度

 

3.capped collection介绍

如前面介绍collection相当于一个表,capped collection就相当于可以指定一个表可以占用空间的最大空间或指定一个表最大可容纳的记录数,个人认为在某些应用场合下这个功能很好用

举例说明:

db.createCollection("mycoll", {capped:true, size:100000})

#指定mycoll这个表最大可以使用100000byte空间,当达到最大空间时再insert记录时,会把最早insert的记录自动删除,好比一个FIFO队列

 

db.createCollection("mycoll", {capped:true, size:100000, max:100});

#指定mycoll这个表最大记录数为100,当第101条记录进来时,最早的记录会被自动删除

如:

> db.createCollection("c1_max_1", {capped:true, size:100000, max:1});  #指定最大记录数为1

{ "ok" : 1 }

> db.c1_max_1.save({a:1})   #插入一条记录

> db.c1_max_1.find()

{ "_id" : ObjectId("4cb7f6efa3f37347a20e37ec"), "a" : 1 }  #列出表所以记录,共一条

> db.c1_max_1.save({a:2})   #再插入一条记录

> db.c1_max_1.find()

{ "_id" : ObjectId("4cb7f6ffa3f37347a20e37ed"), "a" : 2 }  #列出表所以记录,仍为一条,最早的记录被删除

 

作者: george.ma   发布时间: 2010-10-19