zoukankan      html  css  js  c++  java
  • MongoDB的常用命令和增查改删

    数据库操作

    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() #删除与指定过滤器匹配的所有文档
    

       

  • 相关阅读:
    [LeetCode] Largest Number At Least Twice of Others 至少是其他数字两倍的最大数
    [LeetCode] Cut Off Trees for Golf Event 为高尔夫赛事砍树
    [LeetCode] Kth Smallest Number in Multiplication Table 乘法表中的第K小的数字
    [LeetCode] 746. Min Cost Climbing Stairs 爬楼梯的最小损失
    [LeetCode] Prefix and Suffix Search 前后缀搜索
    [LeetCode] Strange Printer 奇怪的打印机
    VMPlayer Ubuntu 16.04 Copy and Paste with Host 主机与宿机之间的复制粘贴
    Solve Error: "errcode": 85005, "errmsg": "appid not bind weapp hint"
    [LeetCode] Find Smallest Letter Greater Than Target 找比目标值大的最小字母
    [LeetCode] 743. Network Delay Time 网络延迟时间
  • 原文地址:https://www.cnblogs.com/52lnamp/p/10179063.html
Copyright © 2011-2022 走看看