我爱编程

MongoDB 基本操作

2017-07-25  本文已影响0人  一颗北上广的心

Get Started

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()函数接受以下四个参数:

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

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;
}
上一篇下一篇

猜你喜欢

热点阅读