MongoDb基本增删改查操作总结

918 阅读3分钟

前言

之前一直习惯用Mysql数据库,换了MongoDb的命令行总是不熟练,这里做一个MongoDb命令行的总结,以后能方便查阅。


MongoDb基本使用

1. 数据库操作

查看数据库

show dbs 

统计数据库信息

use test  # 切换到test数据库

db.stats()         //统计数据信息
{ 
    "db" : "test",     //数据库名
    "collections" : 0, //集合数量
    "views" : 0,
    "objects" : 0,     //文档数量
    "avgObjSize" : 0,  //平均每个文档的大小
    "dataSize" : 0,    //数据占用空间大小,不包括索引,单位为字节
    "storageSize" : 0, //分配的存储空间
    "nuinExtents" : 0, //连续分配的数据块
    "indexes" : 0,     //索引个数
    "indexsize" : 0,   //索引占用空间大小
    "fileSize" : 0,    //物理存储文件的大小
    "ok" : 1 
}

删除数据库

db.dropDatabase ()    //删除当前数据库,db指向当前使用的test数据库

查看该数据库下的集合

db.getCollectionNames()


2. 集合操作

创建集合

db.createCollection(name, options)

eg:db.createCollection("yingSet", {capped:true,size:6142800, max :10000 }) #创建yingSet数据库
                                                options 可以使用的选项
参数类型描述
cappedBoolean(可选)如果为 true,则启用封闭的集合。上限集合是固定大小的集合,它在达到其最大时自动覆盖其最旧的条目。如果指定 true,则还需要指定 size 参数
size数字(可选)指定上限集合的最大大小(以字节为单位)。如果 capped 为 true,那么还需要指定次字段的值
max数字(可选)指定上限集合中允许的最大文档数

如果向一个没有创建的集合中插入文档,那么会先创建这个集合

db.yingSet.insert( {"name": "tom"} )    # db.yingSet指向集合对象


查看该数据库下的集合

show collections
cms_config
cms_page
cms_site
cms_site_server
cms_template
filesystem
fs.chunks
fs.files
sys_dictionary
user_test

重命名集合

db.yingSet.renameCollection( "myset")

删除集合

db.yingSet.drop()


3. 文档操作

插入操作

插入不指定 _id 字段的文档

db.test.insert( { item : "card", qty : 15 })  #向test集合插入数据

插入指定 _id 字段的文档,值 _id 必须在集合中唯一,以避免重复键错误

 db.test.insert(
    { _id: 10, item: "box", qty: 20 }
) 

用变量方式插入文档

do = ({ name: "c语言", price: 40 }) 
db.test.insert(do)


MongoDB 3.2 更新后新增

db.test.insertOne( { item: "card", qty: 15 } );

插入的多个文档

db.test.insertMany([
    { item: "card", qty: 15 },
    { item: "envelope", qty: 20 },
    { item: "stamps", qty:30 }
])


更新修改操作

obj 代表需要更新的对象,如果集合内部已经存在一个与 obj 相同的“_id”的记录,Mongodb 会把 obj 对象替换为集合内已存在的记录;如果不存在,则会插入 obj 对象。

db.collection.save ( obj )

eg:
db.products.save( { _id: 100, item: "watern, qty: 30 })


删除操作

db.test.remove({'title': 'MongoDB'})

db.collection.deleteMany ({})  
db.collection.deleteMany ({ status : "A" })
db.collection.delete.One ({ status : "D" })

查询操作

基本条件查询

db.test.find()
db.test.find().pretty()

                                 MongoDB 与 RDBMS 的查询比较
操作符格式实例与 RDBMS where 语句比较
等于(=){<key> : {<value>}}db.test.find( {price : 24} )where price = 24
大于(>){<key> : {$gt : <value>}}db.test.find( {price : {$gt : 24}} )where price > 24
小于(<){<key> : {$lt : <value>}}db.test.find( {price : {$lt : 24}} )where price < 24
大于等于(>=){<key> : {$gte : <value>}}db.test.find( {price : {$gte : 24}} )where price >= 24
小于等于(<=){<key> : {$lte : <value>}}db.test.find( {price : {$lte : 24}} )where price <= 24
不等于(!=){<key> : {$ne : <value>}}db.test.find( {price : {$ne : 24}} )where price != 24
与(and){key01 : value01, key02 : value02, ...}db.test.find( {name : "《》", price : 24} )where name = "《》" and price = 24
或(or){$or : [{key01 : value01}, {key02 : value02}, ...]}db.test.find( {$or:[{name : "《》"},{price : 24}]} )where name = "《》" or price = 24

查询 age 为 null 的字段

db.test.find({age:null})

限制查询结果的个数

db.test.find().limit(3)

用于对查询结果进行排序,1 是升序,-1 是降序

db.test.find().sort({"price" : 1})

使用 $regex 操作符来设置匹配字符串的正则表达式

db.test.find({tags:{$regex:"MongoDB"}})