MongoDB 基本操作

Get Started

  • Start mongo server:

  • download mongodb

  • create the folder C:/data/db

  • open a cmd, cd the bin folder of mongodb

  • type "mongod" in cmd to start the server.

  • Open MongoDB Enterprise:

  • open a cmd, cd the bin folder of mongodb

  • type "mongo" in cmd to start the Enterprise

  • MongoDB Enterprise > use admin //create root user

  • create a super admin.

MongoDB Enterprise > use admin //create root user
switched to db admin
MongoDB Enterprise > db.createUser({ user: "root",pwd: "root",customData:{name:"root"},roles:[{ role: "userAdminAnyDatabase",db: "admin" }]})

Then you can use this user login any db in mongo. (use xxx; db.auth('root','root'))

MANAGE

show dbs //show all the databases
show collections //show all the collections of the datebase used
db.stats() //show the info of the database used
db.numbers.stats() // show the info of the collection numbers
db.numbers.getIndexes()  //show the indexes of the collection numbers

CREATE DB

MongoDB Enterprise > show dbs
admin  0.000GB
local  0.000GB
MongoDB Enterprise > use tmybang  //create db
switched to db tmybang
MongoDB Enterprise > show dbs  // you can't see it until you add some data into it
admin  0.000GB
local  0.000GB
MongoDB Enterprise > use tmybang
switched to db tmybang
MongoDB Enterprise > db.users.insert({"id":1,"name":"aaa","age":20,"sex":"f"})  // add some 
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > show dbs  // you can see it now!
admin    0.000GB
local    0.000GB
tmybang  0.000GB

DROP DB

MongoDB Enterprise > use dbfordelete
switched to db dbfordelete
MongoDB Enterprise > db.users.insert({"id":1,"name":"aaa","age":20,"sex":"f"})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > show dbs  // has added a db for delete
admin        0.000GB
dbfordelete  0.000GB
local        0.000GB
tmybang      0.000GB
MongoDB Enterprise > use dbfordelete  // choose the db for delete
switched to db dbfordelete
MongoDB Enterprise > db.dropDatabase()  // delete it
{ "dropped" : "dbfordelete", "ok" : 1 }
MongoDB Enterprise > show dbs
admin    0.000GB
local    0.000GB
tmybang  0.000GB

COLLECTION OPERATIONS

MongoDB Enterprise > db.createCollection("product.product") //创建普通collection
{ "ok" : 1 }

//capped collection: 无索引, 不可以删除数据,不可以执行任何会增加文档大小的更新操作
MongoDB Enterprise > db.createCollection("cappedCollection",{capped:true,size:9000}) //创建固定大小collection, 超过部分会被最新的覆盖
{ "ok" : 1 }
MongoDB Enterprise > db.cappedCollection.drop()//删除collection
true
MongoDB Enterprise > db.createCollection("cappedCollection",{capped:true,size:9000,max:1000}) //创建固定大小,文档条数collection,超过的部分会被最新的覆盖
{ "ok" : 1 }
MongoDB Enterprise > db.cappedCollection.isCapped() // 判断是否是固定大小集合
true
MongoDB Enterprise > db.foods.isCapped()
false
MongoDB Enterprise > db.runCommand({"convertToCapped":"foods",size:1000}) //将普通的collection转为固定大小collection
{ "ok" : 1 }

INSERT/SAVE

MongoDB Enterprise > db.users.find()
{ "_id" : ObjectId("5971970abd50d9cb81338f84"), "id" : 1, "name" : "aaa", "age" : 20, "sex" : "f" }  // there is one at first
MongoDB Enterprise > db.users.insert({"id":2,"name":"bbb","age":10,"sex":"f"})  // insert one
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > db.users.save({"id":3,"name":"ccc","age":30,"sex":"m"})  // save one
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > db.users.find()  // there are three now
{ "_id" : ObjectId("5971970abd50d9cb81338f84"), "id" : 1, "name" : "aaa", "age" : 20, "sex" : "f" }
{ "_id" : ObjectId("59719e469b902070b598cbc6"), "id" : 2, "name" : "bbb", "age" : 10, "sex" : "f" }
{ "_id" : ObjectId("59719e599b902070b598cbc7"), "id" : 3, "name" : "ccc", "age" : 30, "sex" : "m" }

UPDATE

--update set name='bbb' where id=1(put the whole entity or just set the name)
MongoDB Enterprise > db.users.update({"id":1},{ "id" : 1, "name" : "bbb", "age" : 20, "sex" : "f" })  
MongoDB Enterprise > db.users.update({"id":1},{ $set: "name" : "bbb"})  
--add new attribute
MongoDB Enterprise > db.users.update({"id":3},{$set:{"foods":["bread","milk"]}})
--add one element to collection attribution if the element not exist
MongoDB Enterprise > db.users.update({"id":3},{$addToSet:{"foods":"meat"}})
--apply addToSet to all the elements in the each collection
MongoDB Enterprise > db.food.update({id:1},{$addToSet:{$each:{"priceHistory":[2,3,6]}}})
--add one element to collection attribution no matter it exist or not
MongoDB Enterprise > db.food.update({id:1},{$push:{priceHistory:2}})
--add all elements to collection attribution
MongoDB Enterprise > db.food.update({id:1},{$pushAll:{priceHistory:[2,3,4,5]}})
--delete the attribute foods
MongoDB Enterprise > db.users.update({"id":3},{$unset:{"foods":1}}) 
--remove the id of the comments
MongoDB Enterprise > db.food.update({id:1},{$unset:{'comments.id':1}})
-- set price=price+2 
MongoDB Enterprise > db.food.update({id:1},{$inc:{price:2}})
--just update the first one mattched
MongoDB Enterprise > db.food.update({price:5},{$set:{name:'potato1'}})
--update all matched
MongoDB Enterprise > db.food.update({price:5},{$set:{name:'potato2'}},false,true)
--if not exist then insert using price and name
MongoDB Enterprise > db.food.update({price:111},{$set:{name:'potato2'}},true)
-- remove the first element in the priceHistory array/ remove the last by 1
MongoDB Enterprise > db.food.update({id:1},{$pop:{priceHistory:-1}})
--rename the column
MongoDB Enterprise > db.food.update({id:1},{$rename:{'comments':'comment'}})
--update priceHistory.0=null
MongoDB Enterprise > db.food.update({id:1},{$unset:{priceHistory.0:1}})
--delete the first element of priceHistory
MongoDB Enterprise > db.food.update({id:1},{$pop:{'priceHistory':-1}})
--delete all 3 from priceHistory
MongoDB Enterprise > db.food.update({id:1},{$pull:{'priceHistory':3}})
--delete all 3 and 4 from priceHistory
MongoDB Enterprise > db.food.update({id:1},{$pullAll:{'priceHistory':[3,4]}})
--find the order item in orders array whose o_id =1, and update the order address($ = the index of the order item found by the query)
MongoDB Enterprise > db.food.update({'id':4,'orders.o_id':1},{$set:{'orders.$.address':"England"}})
--mongo在做大数据更新的时候,会锁表导致其他进程无法访问,所以会暂停更新让出锁一段时间后再锁表更新;但是让出锁可能会导致一致性问题,可以设置atomic参数表明不让锁,一直更新.
MongoDB Enterprise > db.food.update({id:{$lt:10}},{$set:{"weight":1}},false,true,{$atomic:true})

db.collection.update( criteria, objNew, upsert, multi )
update()函数接受以下四个参数:

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

DELETE

MongoDB Enterprise > db.users.find()
{ "_id" : ObjectId("5971970abd50d9cb81338f84"), "id" : 1, "name" : "bbb", "age" : 20, "sex" : "f" }
{ "_id" : ObjectId("59719e469b902070b598cbc6"), "id" : 2, "name" : "bbb", "age" : 10, "sex" : "f" }
{ "_id" : ObjectId("59719e599b902070b598cbc7"), "id" : 3, "name" : "ccc", "age" : 30, "sex" : "m" }
MongoDB Enterprise > db.users.remove({"id":3})  //delete from users where id=3
WriteResult({ "nRemoved" : 1 })
MongoDB Enterprise > db.users.find()
{ "_id" : ObjectId("5971970abd50d9cb81338f84"), "id" : 1, "name" : "bbb", "age" : 20, "sex" : "f" }
{ "_id" : ObjectId("59719e469b902070b598cbc6"), "id" : 2, "name" : "bbb", "age" : 10, "sex" : "f" }
MongoDB Enterprise > db.users.remove({"name":"bbb"})  //delete from users where name='b'
WriteResult({ "nRemoved" : 2 })
MongoDB Enterprise > db.users.remove({"name":"bbb"},1)  //only delete the first one got
MongoDB Enterprise > db.users.remove({})  // truncate users

SELETE

--find all
MongoDB Enterprise > db.users.find()                
--find all and show in a better way
MongoDB Enterprise > db.users.find().pretty()  
-- only select price
MongoDB Enterprise > db.food.find({},{"price":1})
-- only NOT select price
MongoDB Enterprise > db.food.find({},{"price":0})
--where age=20
MongoDB Enterprise > db.users.find({"age":20})          
--where age<20
MongoDB Enterprise > db.users.find({"age":{$lt:20}})     
--where age>20
MongoDB Enterprise > db.users.find({"age":{$gt:20}})    
--where age>=20 
MongoDB Enterprise > db.users.find({"age":{$gte:20}})   
--where age!=20 ; can NOT trigger index
MongoDB Enterprise > db.users.find({"age":{$ne:20}})    
--where age!=20 and name='ccc'
MongoDB Enterprise > db.users.find({"age":{$ne:20},"name":"ccc"})  
--where name='bbb' or name='ccc'
MongoDB Enterprise > db.users.find({$or:[{"name":"ccc"},{"name":"bbb"}]})  
--(name='bbb' or name='ccc') and sex='m'
MongoDB Enterprise > db.users.find({$or:[{"name":"bbb"},{"name":"ccc"}],"sex":"m"}) 
--only return sex
MongoDB Enterprise > db.users.find({"age":10},{"sex":1})    
--name like s%
MongoDB Enterprise > db.users.find({"name":/^s/})   
--name NOT like s%
MongoDB Enterprise > db.users.find({"name":{$not:/^s/}})            
--like %s%
MongoDB Enterprise > db.users.find({"name":/s/})    
--id in (2,3)
MongoDB Enterprise > db.users.find({id:{$in:[2,3]}})        
--id not in (2,3)  can NOT trigger index.
MongoDB Enterprise > db.users.find({id:{$nin:[2,3]}})
--priceHistory has 1 and 3
MongoDB Enterprise > db.food.find({priceHistory:{$all:[1,3]}})
{ "_id" : ObjectId("5994fe25c3600b69c45b6915"), "_class" : "com.test.Food", "id" : 1, "name" : "rice", "price" : 1, "priceHistory" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5994fe25c3600b69c45b6917"), "_class" : "com.test.Food", "id" : 3, "name" : "milk", "price" : 3, "priceHistory" : [ 1, 3, 4 ] }
-- find the data which have priceHistory
MongoDB Enterprise > db.food.find({priceHistory:{$exists:true}})
--同上
MongoDB Enterprise > db.food.find({priceHistory:{$ne:null}})
-- can use the attribute as POJO
MongoDB Enterprise > db.food.find({"comments.id":1}).pretty()
{
        "_id" : ObjectId("5994fe25c3600b69c45b6915"),
        "_class" : "com.test.Food",
        "id" : 1,
        "name" : "rice",
        "price" : 1,
        "priceHistory" : [
                1,
                2,
                3
        ],
        "comments" : {
                "id" : 1,
                "content" : "good"
        }
}
// price history array contains 1
MongoDB Enterprise > db.food.find({"priceHistory":1})
{ "_id" : ObjectId("5994fe25c3600b69c45b6915"), "_class" : "com.test.Food", "id" : 1, "name" : "rice", "price" : 1, "priceHistory" : [ 1, 2, 3 ], "comments" : { "id" : 1, "content" : "good" } }
{ "_id" : ObjectId("5994fe25c3600b69c45b6917"), "_class" : "com.test.Food", "id" : 3, "name" : "milk", "price" : 3, "priceHistory" : [ 1, 3, 4 ] }
//price history array[0] = 1
MongoDB Enterprise > db.food.find({"priceHistory.0":1})
{ "_id" : ObjectId("5994fe25c3600b69c45b6915"), "_class" : "com.test.Food", "id" : 1, "name" : "rice", "price" : 1, "priceHistory" : [ 1, 2, 3 ], "comments" : { "id" : 1, "content" : "good" } }
{ "_id" : ObjectId("5994fe25c3600b69c45b6917"), "_class" : "com.test.Food", "id" : 3, "name" : "milk", "price" : 3, "priceHistory" : [ 1, 3, 4 ] }
-- find the food whose priceHistory.size is 3
MongoDB Enterprise > db.food.find({"priceHistory":{$size:3}})
// find the food which has the priceHistoryItem that xxx is 1 and yyy is 2.
MongoDB Enterprise > db.food.find({"priceHistory":{$elemMatch:{xxx:1,yyy:2}}})
--price%3=0, can NOT trigger index
MongoDB Enterprise > db.food.find({"price":{$mod:[3,0]}})
--get data with the first priceHistory
MongoDB Enterprise > db.food.find({},{"priceHistory":{$slice:1}})
--get data with the last priceHistory
MongoDB Enterprise > db.food.find({},{"priceHistory":{$slice:-1}})
--get data with the priceHistory index between 1 and 2
MongoDB Enterprise > db.food.find({},{"priceHistory":{$slice:[1,2]}})
--priceHistory 树组中包含1的
MongoDB Enterprise > db.food.find({"priceHistory":1})
--priceHistory[0]=1
MongoDB Enterprise > db.food.find({"priceHistory.0":1})

--mongo always sort -> skip -> limit
--get the first one
MongoDB Enterprise > db.users.find().limit(1)  
--get the second one
MongoDB Enterprise > db.users.find().skip(1).limit(1)  
--order by id asc
MongoDB Enterprise > db.users.find().sort({"id":1})  
--order by id desc
MongoDB Enterprise > db.users.find().sort({"id":-1})  

CREATE INDEX

//create unique index
MongoDB Enterprise > db.food.ensureIndex({id:1},{unique:true})
// craete union index
MongoDB Enterprise > db.users.ensureIndex({"id":1,"name":1})    
//create index background to enable CRUD while creating index
MongoDB Enterprise > db.food.ensureIndex({id:1},{background:true})                                              
//recreate all indexes
MongoDB Enterprise > db.food.reIndex()
//explain search
db.users.find().explain(true)
MongoDB Enterprise > db.users.getIndexes() //查看索引
MongoDB Enterprise > db.users.dropIndex({"cardno":1})//删除索引

AGGREGATE

MongoDB Enterprise > db.users.aggregate([{$group :{_id:"$age", result:{$sum:1}}}])  // select age, count(1) from users group by age
{ "_id" : 20, "result" : 2 }
{ "_id" : 40, "result" : 1 }
{ "_id" : 10, "result" : 1 }
MongoDB Enterprise > db.users.aggregate([{$group :{_id:"$age", result:{$avg:"$id"}}}])  //select age, avg(id) from users group by age
{ "_id" : 20, "result" : 2.5 }
{ "_id" : 40, "result" : 3 }
{ "_id" : 10, "result" : 2 }
MongoDB Enterprise > db.users.aggregate([{$group :{_id:"$age", result:{$min:"$id"}}}])  //select age, min(id) from users group by age
{ "_id" : 20, "result" : 1 }
{ "_id" : 40, "result" : 3 }
{ "_id" : 10, "result" : 2 }
MongoDB Enterprise > db.users.aggregate([{$group :{_id:"$age", result:{$max:"$id"}}}])  //select age, max(id) from users group by age
{ "_id" : 20, "result" : 4 }
{ "_id" : 40, "result" : 3 }
{ "_id" : 10, "result" : 2 }
-- select distinct(price) from food where price>3
MongoDB Enterprise > db.food.distinct("price",{price:{$gt:3}})

copy

https://www.w3cschool.cn/mongodb/mongodb-sharding.html

分片

backup

monitor

PS

  • 自动补全命令: 连续按两个TAB可自动补全命令
  • 查看mongo原码, 输入不带括号的命令即可, eg:
MongoDB Enterprise > db.collection.find
function (query, fields, limit, skip, batchSize, options) {
    var cursor = new DBQuery(this._mongo,
                             this._db,
                             this,
                             this._fullName,
                             this._massageObject(query),
                             fields,
                             limit,
                             skip,
                             batchSize,
                             options || this.getQueryOptions());

    var connObj = this.getMongo();
    var readPrefMode = connObj.getReadPrefMode();
    if (readPrefMode != null) {
        cursor.readPref(readPrefMode, connObj.getReadPrefTagSet());
    }

    var rc = connObj.getReadConcern();
    if (rc) {
        cursor.readConcern(rc);
    }

    return cursor;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,948评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,371评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,490评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,521评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,627评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,842评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,997评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,741评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,203评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,534评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,673评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,339评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,955评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,770评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,000评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,394评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,562评论 2 349

推荐阅读更多精彩内容

  • 安装 配置环境 mongodb安装完毕后,默认安装路径在/usr/local/Cellar/mongodb/3.4...
    bd4d0d78f248阅读 5,737评论 0 53
  • 系统相关 安装MongoDB 启动MongoDB服务器 连接MongoDB服务器,启动客户端 数据库相关 创建数据...
    DongGuangqing阅读 245评论 0 0
  • 创建数据库 打印数据库列表 ** MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放...
    陈小陌丿阅读 266评论 0 0
  • 原文链接 安装/卸载MongoDB 查看MongoDB版本信息 开启/关闭MongoDB服务 查看MongoDB是...
    sssnowyue阅读 239评论 0 0
  • mongodb需要先启动一个服务器进程(mongod命令),然后再启动客户端进程(mongo命令)。安装完成之后如...
    fooke阅读 582评论 0 0