xy123321 发表于 2015-11-11 09:54:48

Mongodb数据库使用

一、启动MongoDB
1.服务器启动方式:


mongod --dbpath=c:\db --logpath=c:\mongo\logs\mongodb.log

dbpath为数据库本地位置  
logpath为日志输出位置(可以省略)



注:本地位置需要手动创建



2.客户端启动方式


mongo localhost:27017
  
27017为服务器端默认启动端口;



3.可以采用更加系统化的配置方式:


cat /etc/mongodb.cnf
dbpath=/data/db/

启动客户端的时候:  


mongod -f /etc/mongodb.cnf

4.Daemon模式启动  



在服务器端启动代码的最后加上 --fork



但是,好像window端无法使用;而且mac上却可以,也许是window不支持;



二、插入记录


a={name:"will"};

如上代码,Mongodb的数据格式类似json,而插入数据的方式如下:  


db.things.save(a);

可以通过下面代码查看数据:  


db.things.find();
  
注:
1.Mongodb在插入数据之前不需要预先创建集合,在第一插入数据时候自动创建(容易出错)
2.可以存储任何结构的数据
3.每次插入的时候都会有一个ID 叫做_id



注:
Mongodb可以采用js的编程语法遍历数据,如下代码:


for(var i=0;i<10;i++)db.things.save({x:4,j:i});
  
可以使用这样的语句插入



三、查询方式
普通查询:
1.


var cursor = db.things.find();
while(cursor.hasNext())printjson(cursor.next());
printjson(cursor);
  
2.


db.things.find().forEach(printjson());
  
3.


var arr = db.things.find().toArray();


  
条件查询:
1.db.things.find({name:&quot;will&quot;})
2.findOne():只返回游标的第一条数据
3.限制limit
db.things.find().limit(4);



四、修改记录


db.things.update({name:&quot;will&quot;},{$set:{name:&quot;will_new&quot;}});
  



五、删除记录


db.things.remove();
  
六、高级查询
1.条件操作符


$lt    <
$lte   <=
$gt    >
$gte   >=
  
例如:db.collection.find({&quot;field&quot;:{$gt:value}});



2.$all 匹配满足所有[]内的数据


db.collection.find({age:{$all:}});
  



3.$exists 判断字符是否存在


db.collection.find({age:{$exists:true}});//所有存在age字段的记录
db.collection.find({age:{$exists:false}});//所有不存在age字段的记录
  
4.Null值处理


db.collection.find({age:null});
  



注:null和不存在不一样;



5.$mod 取模运算


db.collection.find({age:{$mod}});//查询age取模6等于1的数据
  
6.$ne 不等于


db.collection.find({age:{$ne:7}});//查询age不等于7的
  
7.$in 包含 $nin 不包含


db.collection.find({age:{$in:}});//查询age在7 8之间的
  



8.$size 数组元素个数


{name:&quot;will&quot;,xxx:};
db.collection.find({xxx:{$size:3}});
  



9.支持正则表达式



10.count 查询记录条数


db.collection.find().count();
db.collection.count();
  
11.skip限制记录起点


db.collection().skip(5).limit(3)
  
12.sort 排列


db.collection().sort({age:1});//升序 asc
db.collection().sort({age:-1});//降序 desc
  



七、游标


for(var i = db.collection.find();c.hasNext();){
c.next();
}
  
八、存储过程
用js支持存储过程,这部分没有学习 就不做总结了























































版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: Mongodb数据库使用