关于MongoDb的简单入门(一)

2015-11-21 01:50:42 · 作者: · 浏览: 14
下载完成mongodb后,要在环境变量中加入 "目录\mongodb\bin"

打开cmd窗口
--开启mongodb服务
mongod -dbpath "D:\mongodb\db"

--注册服务
mongod -dbpath "D:\mongodb\db" -logpath "D:\mongodb\log\mongodb.log" -install -serviceName "MongoDB"

--启动服务
net start MongoDB;

--查看帮助
db.help();

--创建库(库名为:zyh)
use zyh;

--查看当前库下的集合
show collections;

mongodb中没有表 只有集合
--创建集合
1.直接向集合中添加数据,如果该集合不存在,则会自动创建 (集合名为:yc)
db.yc.insert({"_id":1001,"name":"yc"});

此时使用命令show collections会发现有两个集合:
system.indexes; 索引集合
yc;

2.db.createCollection("navy");

--删除集合
db.yc.drop();

--删除记录(文档)
db.collection_name.remove({条件});
db.yc.remove({"_id":{"$ne":1001}}); //$ne:不等于 $lt:小于 $gt:大于 $lte:小于等于 $gte:大于等于

--向集合中添加多条记录
db.yc.insert([{"_id":1002,"name":"天天","sex":"男"},{"_id":1003,"name":"当当","sex":"女"}]);

--查看集合中的数据(.limit为分页)
db.yc.find();


数据类型:
null: {"x":null}
boolean: {"x":true}
数值: {"x":3.14} {"x":3} NumberInt("3") NumberLong("3")
字符串: {"x":"hello"}
日期: {"x":new Date()}
正则表达式: {"x":/hello/ig}
数组:{"x":[1,2,3]}
内嵌文档:{"x":{"foo":{bar}}}
对象id:{"x":ObjectId()}
二进制:
代码:{"x":function(){}}

--如果存在,则修改,如果不存在,则添加。
db.yc.save({"_id":1004,"name":"navy1"});

--修改
db.yc.update({条件},{要修改的数据});
db.yc.update({"_id":1002},{"name":"scott1","sex":"F"})

db.yc.insert({"_id":1001,"url":"www.hyycinfo.com","pageViews":1});
db.yc.insert({"_id":1002,"company":"yc","url":"www.hyycinfo.com","pageViews":1});

--修改器
$inc 增加对应的值
db.yc.updat
e({"_id":1001},{"$inc":{"pageViews":1}}); --将_id为1001的文档中的pageViews键的值增加1 $set db.yc.update({"_id":1002},{"name":"scott1","sex":"F"}) db.yc.update({"_id":1002},{"$set":{"name":"scott1","sex":"F"}}) --将company变成一个数组 db.yc.update({"_id":1002},{"$set":{"company":["yc","nh","navy"]}}) --删除键 db.yc.update({"_id":1002},{"$unset":{"company":1}}) --删除记录1002中的company键 --数组修改器 $push 向数组中添加值,可能会出现重复的值 db.yc.update({"_id":1002},{"$push":{"company":"sc"}}); $each db.yc.update({"_id":1002},{"$push":{"company":{"$each":["hg","rc","jm"]}}}); $slice 指定最大的长度,它的值必须是负数,表示保留最后的n个值 db.yc.update({"_id":1002},{"$push":{"company":{"$each":["yc1","yc2","yc"],"$slice":-10}}}); $pop 从数组中删除一个元素 key:1 从数据的末尾开始 key:-1从头部开始 db.yc.update({"_id":1002},{"$pop":{"company":1}}) $pull从数组中删除匹配的值 db.yc.update({"_id":1002},{"$pull":{"company":"sc"}}) db.yc.insert({ "_id":1005, "content":"今天吃的怎么样?", "comments":[ {"comment":"好","count":0}, {"comment":"很好","count":0}, {"comment":"非常好","count":0} ] }) --通过数组下标访问 db.yc.update({"_id":1004},{"$inc":{"comments.1.count":1}}); db.yc.update({"comments.comment":"好"},{"$inc":{"comments.$.count":1}}) db.yc.update({"comments.comment":"很好"},{"$set":{"comments.$.comment":"很很好"}}) --MongoDB默认每次只修改一个文档,如果需要修改所有满足条件的记录,则需在后面添加条件{multi:true} db.yc.update({"comments.comment":"好"},{"$inc":{"comments.$.count":1}},{multi:true}) db.yc.update({"comments.comment":"好"},{"$inc":{"comments.$.count":1}},false,true) --删除 db.yc.remove({条件}); --查询 db.yc.find(); --查询所有记录 db.yc.findOne(); --查询第一条记录 db.yc.find({"_id":1001}); --where ke