mongodb的常见命令
【数据库的操作】
1.增
use config 如果数据库不存在 则创建并切换到数据库 存在则直接切换到指定的数据库
2.查
show dbs 查看所有的数据库 相当于mysql中的show databases
3.删
use config 先切换到要删除的数据库下
db.dropDatabase() 删除当前数据库
【集合操作】
1.创建集合
db.createCollection(name,option)
name:要创建集合的名称
options:可选参数 指定有关内存大小及索引的选项
2.删除集合
db.collection.drop()
3.查看所有的集合
show collections
【文档操作】
1.增
db.collection_name.insert({document})#如果数据库中不存在集合则创建并插入数据
db.collection_name.insert({document},{document})插入多条数据
db.collection_name.save(document)
注意:insert和save的区别是:用insert插入在集合中已经存在相同的"_id"值,执行插入操作会报异常
用save插入如果集合中没有相同的"_id"值就执行插入操作有的话就执行覆盖掉原来的值相当于修改操作
2.删
db.collection_name.remove({条件},属性)
db.collection_name.remove()#删除集合中所有的数据
db.collection_name.remove({‘sex’:‘女’})#按条件删除
db.collection_name.remove({‘name’:‘张无忌’},2)#删除几条
3.改
db.collection.update({
查询的条件,
更新的语句,
附加的参数
})
upsert:可选如果不存在update的记录 是否插入objNew,true为插入默认时false不插入
multi:可选 mongodb默认时false 只更新找到的第一条记录,如果这个参数为true 就把按条件查出来的多条记录全部更新
【实例】
db.collection_name.update({‘name’:‘张三’},{‘name’:‘张三丰’})
如果有多条数据只修改第一条 覆盖原来的数据
db.collection_name.update({‘name’:‘张三’},{$set:{‘name’:‘张无忌’}})#只更改某个key的value值用set
4.查
db.collection_name.find()
1.查找key=value的数据
db.collection.find({ “key” : value })
2.key > value
db.collection.find({ “key” : { $gt: value } })
3.key < value
db.collection.find({ “key” : { $lt: value } })
4.key >= value
db.collection.find({ “key” : { $gte: value } })
5.key <= value
db.collection.find({ “key” : { $lte: value } })
6.value1 < key <value2
db.collection.find({ “key” : { $gt: value1 , $lt: value2 } })
7.key <> value
db.collection.find({ “key” : { $ne: value } })
8.取模运算,条件相当于key % 10 == 1 即key除以10余数为1的
db.collection.find({ “key” : { $mod : [ 10 , 1 ] } })
9.不属于,条件相当于key的值不属于[ 1, 2, 3 ]中任何一个
db.collection.find({ “key” : { $nin: [ 1, 2, 3 ] } })
10.属于,条件相当于key等于[ 1, 2, 3 ]中任何一个
db.collection.find({ “key” : { KaTeX parse error: Expected 'EOF', got '}' at position 17: …n: [ 1, 2, 3 ] }̲ })
11.size 数量、尺寸,条件相当于key的值的数量是1(key必须是数组,一个值的情况不能算是数量为1的数组)
db.collection.find({ “key” : { KaTeX parse error: Expected 'EOF', got '}' at position 9: size: 1 }̲ })
12.exists 字段存在,true返回存在字段key的数据,false返回不存在字度key的数据
db.collection.find({ “key” : { KaTeX parse error: Expected 'EOF', got '}' at position 21: …s : true|false }̲ })
13.正则,类似lik…/ })
14.$or或 (注意:MongoDB 1.5.3后版本可用),符合条件a=1的或者符合条件b=2的数据都会查询出来
db.collection.find({ $or : [{a : 1}, {b : 2} ] })
15.符合条件key=value ,同时符合其他两个条件中任意一个的数据
db.collection.find({ “key”: value , KaTeX parse error: Expected 'EOF', got '}' at position 30: …} , { b : 2 }] }̲)
16.内嵌对象中的值匹配,…not之后就能获得相反的集合。
db.collection.find({ “key”: { not:/val.valnot : /^val.valnot:/val.val/i } })
18.$where中的value,就是我们非常熟悉,非常热爱的js
db.collection.find({ $where:function(){return this.name==“joe”} })