欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MongoDB的常用命令和增查改删

程序员文章站 2024-01-17 10:43:28
数据库操作 Mongodb MySQL 查询库 show databases | show dbs show databases 选中库 use databaseName use databaseName 查询表 show tables | show collections show tables ......

数据库操作

mongodb

mysql

查询库

show databases | show dbs

show databases

选中库

use databasename

use databasename

查询表

show tables | show collections

show tables

创建表

db.createcollection(‘collectionname’)

create table tablename...

删除表

db.collectionname.drop

drop table tablename

删除库

db.dropdatabase

drop database databasename

添加表数据

db.collectionname.insert

insert

查询表数据

db.collectionname.find

select

修改表数据

db.collectionname.update

update

删除表数据

db.collectionname.remove

delete

如上述所示,mongodb同样兼容了部分传统数据库的命令,其中有必要说一下的是mongodb中创建库采用的是隐式创建,即在use 一个不存在的库时就会变为创建库,use databasename 有则选中无则创建,但这里还没有创建完毕,需要进一步创建表才算创建完毕;同时创建表时也允许隐式创建,db.collectionname.insert 往一个不存在的表中添加数据就会先创建表再添加数据

一:常用命令

1.1:查看当前的数据库

> show dbs
admin   0.000gb
config  0.000gb
local   0.000gb
shop    0.000gb
> show databases
admin   0.000gb
config  0.000gb
local   0.000gb
shop    0.000gb

1.2:选中库

> use shop
switched to db shop

1.3:查看

> show collections
user
> show tables
user  

1.4.1:创建库/表

> use good
switched to db good
> db.createcollection('items')  
{ "ok" : 1 }

1.4.2:创建库/表第二种方式

> use cate
switched to db cate
> db.catelist.insert({"_id":1,"catename":"fast"})
writeresult({ "ninserted" : 1 })

1.4.3:在创建库时如果没有创建表,库也会创建失败

> use cate
switched to db cate
> show dbs
admin   0.000gb
config  0.000gb
good    0.000gb
local   0.000gb
shop    0.000gb

1.5:删除表

> db.catelist.drop()
true

1.6:删除库

> use good 
switched to db good
> db.dropdatabase()
{ "dropped" : "good", "ok" : 1 }

1.7:使用db.help()查看更多方法

> db.help()
db methods:
        db.admincommand(nameordocument) - switches to 'admin' db, and runs command [just calls db.runcommand(...)]
        db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
        db.auth(username, password)
        db.clonedatabase(fromhost) - deprecated
        db.commandhelp(name) returns the help for the command
        db.copydatabase(fromdb, todb, fromhost) - deprecated
        db.createcollection(name, {size: ..., capped: ..., max: ...})
        db.createview(name, viewon, [{$operator: {...}}, ...], {viewoptions})
        db.createuser(userdocument)
        db.currentop() displays currently executing operations in the db
        db.dropdatabase()
        db.eval() - deprecated
        db.fsynclock() flush data to disk and lock server for backups
        db.fsyncunlock() unlocks server following a db.fsynclock()
        db.getcollection(cname) same as db['cname'] or db.cname
        db.getcollectioninfos([filter]) - returns a list that contains the names and options of the db's collections
        db.getcollectionnames()
        db.getlasterror() - just returns the err msg string
        db.getlasterrorobj() - return full status object
        db.getlogcomponents()
        db.getmongo() get the server connection object
        db.getmongo().setslaveok() allow queries on a replication slave server
        db.getname()
        db.getpreverror()
        db.getprofilinglevel() - deprecated
        db.getprofilingstatus() - returns if profiling is on and slow threshold
        db.getreplicationinfo()
        db.getsiblingdb(name) get the db at the same server as this one
        db.getwriteconcern() - returns the write concern used for any operations on this db, inherited from server object if set
        db.hostinfo() get details about the server's host
        db.ismaster() check replica primary status
        db.killop(opid) kills the current operation in the db
        db.listcommands() lists all the db commands
        db.loadserverscripts() loads all the scripts in db.system.js
        db.logout()
        db.printcollectionstats()
        db.printreplicationinfo()
        db.printshardingstatus()
        db.printslavereplicationinfo()
        db.dropuser(username)
        db.repairdatabase()
        db.reseterror()
        db.runcommand(cmdobj) run a database command.  if cmdobj is a string, turns it into {cmdobj: 1}
        db.serverstatus()
        db.setloglevel(level,<component>)
        db.setprofilinglevel(level,slowms) 0=off 1=slow 2=all
        db.setwriteconcern(<write concern doc>) - sets the write concern for writes to the db
        db.unsetwriteconcern(<write concern doc>) - unsets the write concern for writes to the db
        db.setverboseshell(flag) display extra information in shell output
        db.shutdownserver()
        db.stats()
        db.version() current version of the server

二.增:db.collectionname.insert(document);

2.1: 增加单篇文档,如果未指定_id会自动生成:

> use shop
switched to db shop
> db.createcollection('order')
{ "ok" : 1 }
> db.order.insert({"ordercode":"f3k32ir45o","price":150.00})
writeresult({ "ninserted" : 1 })
> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "ordercode" : "f3k32ir45o", "price" : 150 }

2.2:增加单个文档并指定_id

> db.order.insert({"_id":2,"ordercode":"f3k32ir45o","price":150.00})
writeresult({ "ninserted" : 1 })
> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "ordercode" : "f3k32ir45o", "price" : 150 }
{ "_id" : 2, "ordercode" : "f3k32ir45o", "price" : 150 }

2.3:增加多个文档

> db.order.insert([{"ordercode":"f3k32ir41o","price":1020.00},{"_id":4,"ordercode":"ew3213fw1324","price":11.11}])
bulkwriteresult({
        "writeerrors" : [ ],
        "writeconcernerrors" : [ ],
        "ninserted" : 2,
        "nupserted" : 0,
        "nmatched" : 0,
        "nmodified" : 0,
        "nremoved" : 0,
        "upserted" : [ ]
})
> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "ordercode" : "f3k32ir45o", "price" : 150 }
{ "_id" : 2, "ordercode" : "f3k32ir45o", "price" : 150 }
{ "_id" : objectid("5c2334cca479af93b5192dac"), "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "_id" : 4, "ordercode" : "ew3213fw1324", "price" : 11.11 }

2.4:mongodb3.2版本中新增两个插入方法:

db.collection.insertone() //将单个文档插入集合中
db.collection.insertmany() //将多个文档插入集合中

三:查:db.collection.find(查询表达式,查询的属性);

3.1:查询所有数据

> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "ordercode" : "f3k32ir45o", "price" : 150 }
{ "_id" : 2, "ordercode" : "f3k32ir45o", "price" : 150 }
{ "_id" : objectid("5c2334cca479af93b5192dac"), "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "_id" : 4, "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.2:查询所有文档的指定属性(_id属性默认查询)

> db.order.find({},{ordercode:1})
{ "_id" : objectid("5c233308a479af93b5192daa"), "ordercode" : "f3k32ir45o" }
{ "_id" : 2, "ordercode" : "f3k32ir45o" }
{ "_id" : objectid("5c2334cca479af93b5192dac"), "ordercode" : "f3k32ir41o" }
{ "_id" : 4, "ordercode" : "ew3213fw1324" }

3.3:查询所有文档的指定属性且不查询_id

> db.order.find({},{ordercode:1,_id:0}) #属性为1表示查询,为0表示过滤
{ "ordercode" : "f3k32ir45o" }
{ "ordercode" : "f3k32ir45o" }
{ "ordercode" : "f3k32ir41o" }
{ "ordercode" : "ew3213fw1324" }

3.4:查询所有ordercode属性值为f3k32ir45o的文档中的price属性且不查询_id属性

> db.order.find({"ordercode":"f3k32ir45o"},{"price":1,_id:0})
{ "price" : 150 }
{ "price" : 150 }

3.5:比较查询运算符

3.5.1: $gt(大于)

> db.order.find({"price":{$gt:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir41o", "price" : 1020 }

3.5.2:$gte(大于等于)

> db.order.find({"price":{$gte:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir41o", "price" : 1020 }

3.5.3:$lt(小于)

> db.order.find({"price":{$lt:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.5.4:$lte(小于等于)

> db.order.find({"price":{$lte:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.5.5:$eq(等于)

> db.order.find({"price":{$eq:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }

#or

> db.order.find({"price":150},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }

3.5.6:$ne(不等于)

> db.order.find({"price":{$ne:150}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.5.7:$in(数组中指定的任何值,相当于mysql的in)

> db.order.find({"price":{$in:[11.11,1020]}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.5.8:$nin(不在指定的数组中)

> db.order.find({"price":{$nin:[150,1020]}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.6:逻辑查询运算符

3.6.1:$and(连接查询子句)

> db.order.find({$and:[{"ordercode":"f3k32ir45o"},{"price":150}]},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }

3.6.2:$not(返回不匹配指定条件的文档)

> db.order.find({"price":{$not:{$gte:150}}},{"ordercode":1,"price":1,"_id":0})  #返回price不大于等于150的文档,也就是返回price小于150的文档
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.6.3:$nor(连接查询子句并返回所有无法匹配指定条件的文档)

> db.order.find({$nor:[{"ordercode":"f3k32ir45o"},{"price":150}]},{"ordercode":1,"price":1,"_id":0})  #返回ordercode不等于f3k32ir45o并且price不等于150的文档
{ "ordercode" : "f3k32ir41o", "price" : 1020 } { "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.6.4:$or(返回匹配任一条件的文档,相当于mysql的or)

> db.order.find({$or:[{"price":11.11},{"price":1020}]},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.7:元素查询运算符

3.7.1:$exists(匹配具有指定字段的文档)

> db.order.find({"price":{$exists:true}},{"ordercode":1,"price":1,"_id":0})  #$exists为true匹配具有指定字段的文档
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }
> db.order.find({"price":{$exists:false}},{"ordercode":1,"price":1,"_id":0})  #$exists为false匹配不具有指定字段的文档

3.7.2:$type(匹配指定类型的文档)

> db.order.find({"ordercode":{$type:2}},{"ordercode":1,"price":1,"_id":0})  #$type可使用数字别名 2表示字符串
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir45o", "price" : 150 }
{ "ordercode" : "f3k32ir41o", "price" : 1020 }
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.8:$regex(正则匹配)

> db.order.find({"ordercode":{$regex:/^e/}},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "ew3213fw1324", "price" : 11.11 }

3.9:findone(查询单个文档)

> db.order.findone({"ordercode":"f3k32ir45o"},{"ordercode":1,"price":1,"_id":0})
{ "ordercode" : "f3k32ir45o", "price" : 150 }

四:改:db.user.update(查询表达式,修改的新值,选项{upsert:true/false,multi:true/false})

4.1:$set(设置文档中字段的值,如果设置的字段不存在则创建该字段)

> db.order.update({_id:4},{$set:{"ordercode":"wfiq13u321ue2","price":111}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "ordercode" : "wfiq13u321ue2", "price" : 111 }

4.2:$unset(删除指定字段)

> db.order.update({_id:4},{$unset:{"ordercode":""}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })

4.3:$inc(按指定的数量增加字段的值)

{ "_id" : 4, "price" : 111, "type" : 1 }
> db.order.update({_id:4},{$inc:{"price":2}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 113, "type" : 1 }

4.4:$min(指定值小于现有字段值才更新,当指定的字段不存在时变为设置该字段为指定的值)

> db.order.update({_id:4},{$min:{"price":110}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 110, "type" : 1 }

4.6:$max(指定值大于现有字段值才更新,当指定的字段不存在时变为设置该字段为指定的值)

> db.order.update({_id:4},{$max:{"price":120}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 120, "type" : 1 }

4.7:$mul(将字段的值乘以指定的值)

> db.order.update({_id:4},{$mul:{"price":2}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 240, "type" : 1 }

4.8:$rename(重命名字段)

> db.order.update({_id:4},{$rename:{"price":"money"}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "type" : 1, "cate" : 0, "money" : 240 }

4.9:在mongodb3.2版本中新增三个修改方法:

db.collection.updateone()   //更新与指定过滤器匹配的单个文档
db.collection.updatemany()  //更新与指定过滤器匹配的所有文档
db.collection.replaceone()  //替换与指定过滤器匹配的单个文档

4.10:带可选条件的修改操作(upsert:true/false,multi:true/false)

--upsert  默认为false,无相应记录时是否添加

--multi  默认为false, 是否作用于多条

> db.order.update({},{$set:{"price":2000}},{upsert:true,multi:true})
writeresult({ "nmatched" : 4, "nupserted" : 0, "nmodified" : 4 })
> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "price" : 2000 }
{ "_id" : 2, "ordercode" : "f3k32ir45o", "price" : 2000 }
{ "_id" : objectid("5c2334cca479af93b5192dac"), "ordercode" : "f3k32ir41o", "price" : 2000 }
{ "_id" : 4, "price" : 2000 }

五:删除: db.collection.remove(查询表达式, 选项{justone:true/flase})

5.1:删除指定查询条件的所有文档

> db.order.remove({"_id":4})
writeresult({ "nremoved" : 1 })
> db.order.find()
{ "_id" : objectid("5c233308a479af93b5192daa"), "price" : 2000 }
{ "_id" : 2, "ordercode" : "f3k32ir45o", "price" : 2000 }
{ "_id" : objectid("5c2334cca479af93b5192dac"), "ordercode" : "f3k32ir41o", "price" : 2000 }

5.2:删除指定查询条件中所有文档的第一个即指定可选参数justone:true

> db.order.remove({},true)
writeresult({ "nremoved" : 1 })
> db.order.find()
{ "_id" : 2, "price" : 1000 }
{ "_id" : 3, "price" : 1000 }
{ "_id" : 4, "price" : 1000 }

5.3:mongodb3.2版本中新增两个删除方法:

db.collection.deleteone()  #删除与指定过滤器匹配的单个文档
db.collection.deletemany() #删除与指定过滤器匹配的所有文档