mongodb命令行操作

来源:互联网 发布:php 生成flash 编辑:程序博客网 时间:2024/06/03 12:28
http://www.iloveher.com.cn
http://112.74.73.115
----------------------------------------------------------------------------------------------

1. 安装mongodb

环境: ubuntu 14.04
apt-get install mongodb
2.启动
mongod &
mongo命令进入命令行



3. 启动时遇到的问题
unbuntu下启动mongod时报
MongoDB:Unclean shutdown detected
解决方法:
mongod --repair

4. 数据库操作(增删改查)
db.hello2.insert({"name":"derry","age":20,"sex":"male"})
db.hello2.insert({"name":"derry2","age":23,"sex":"male"})
db.hello2.insert({"name":"derry3","age":25,"sex":"female"})
db.hello2.insert({"name":"derry4","age":26,"sex":"male"})
db.hello2.insert({"name":"derry5","age":10,"sex":"famale"})
db.hello2.insert({"name":"derry6","age":19,"sex":"male"})
db.hello2.insert({"name":"derry7","age":20,"sex":"famale"})
db.hello2.insert({"name":"derry8","age":30,"sex":"male"})
db.hello2.insert({"name":"dxt","age":20,"sex":"famale"})
db.hello2.insert({"name":"test2","age":30,"sex":"male"})
查询所有记录
db.hello2.find()
查询年龄20岁以上的
db.hello2.find({age:{$gt:20}})

查询name中包含'derry'的数据
db.hello2.find({name:/derry/})
以derry开头
db.hello2.find({name:/^derry/})

年龄大于20的male
db.hello2.find({age:{$gt:30},sex:male})  

年龄小于15 或name以dxt开头
db.hello2.find({$or:[{age:{$lt:15}},{name:/^dxt/}]})

美化显示结果(格式化)
db.hello2.find().pretty()

显示结果的前几条
db.hello2.find().limit(3)

查询第一条以后的所有
db.hello2.find().skip(1)

对结果排序

db.hello2.find().sort({age:-1}) 对年龄降序
db.hello2.find().sort({age:1}) 对年龄升序


统计记录数
db.hello2.find().count()


删除
db.hello2.remove({name:/^dxt/})


 赋值更新
db.collection.update(criteria, objNew, upsert, multi )
criteria:update的查询条件,类似sql update查询内where后面的
objNew:update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的。
upsert : 如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。


> db.hello2.find({name:'derry'})
{ "_id" : ObjectId("56d686c5dd82d6c591b9e952"), "name" : "derry" }
{ "_id" : ObjectId("56d68a76dd82d6c591b9e955"), "name" : "derry", "age" : 20, "sex" : "male" }
> db.hello2.update({name:'derry'},{$set:{age:100}},false,true)
> db.hello2.find({name:'derry'})
{ "_id" : ObjectId("56d68a76dd82d6c591b9e955"), "name" : "derry", "age" : 100, "sex" : "male" }
{ "_id" : ObjectId("56d686c5dd82d6c591b9e952"), "age" : 100, "name" : "derry" }

0 0
原创粉丝点击