tar -zxvf mongodb-linux-x86_64-ubuntu1604-3.4.0.tgz
sudo mv -r mongodb-linux-x86_64-ubuntu1604-3.4.0/ /usr/local/mongodb
export PATH=/usr/local/mongodb/bin:$PATH
默認端口27017python
啓動 sudo service mongod start
linux
sudo service mongod stop
mongo
db查看當前數據庫名稱 db.stats()查看當前數據庫信息
exit 或ctrl+c
db
show dbs
use 數據庫名稱
db.dropDatabase()
db.createCollection(name, options)
db.createCollection("stu")
db.createCollection("sub", { capped : true, size : 10 } )
show collections
db.集合名稱.drop()
db.集合名稱.insert(document)
db.stu.insert({name:'gj',gender:1})
s1={_id:'20160101',name:'hr'} s1.gender=0 db.stu.insert(s1)
db.集合名稱.find()
db.集合名稱.update( <query>, <update>, {multi: <boolean>} )
db.stu.update({name:'hr'},{name:'mnc'})
db.stu.insert({name:'hr',gender:0}) db.stu.update({name:'hr'},{$set:{name:'hys'}})
db.stu.update({},{$set:{gender:0}},{multi:true})
db.集合名稱.save(document)
若是文檔的_id已經存在則修改,若是文檔的_id不存在則添加web
例6正則表達式
db.stu.save({_id:'20160102','name':'yk',gender:1})
db.stu.save({_id:'20160102','name':'wyk'})
db.集合名稱.remove( <query>, { justOne: <boolean> } )
db.stu.remove({gender:0},{justOne:true})
db.stu.remove({})
db.createCollection('sub',{capped:true,size:10})
db.sub.insert({title:'linux',count:10}) db.sub.find()
db.sub.insert({title:'web',count:15}) db.sub.find()
db.sub.insert({title:'sql',count:8}) db.sub.find()
db.sub.insert({title:'django',count:12}) db.sub.find()
db.sub.insert({title:'python',count:14}) db.sub.find()
db.集合名稱.find({條件文檔})
db.集合名稱.findOne({條件文檔})
db.集合名稱.find({條件文檔}).pretty()
db.stu.find({name:'gj'})
db.stu.find({age:{$gte:18}})
db.stu.find({age:{$gte:18},gender:1})
db.stu.find({$or:[{age:{$gt:18}},{gender:1}]})
db.stu.find({$or:[{age:{$gte:18}},{gender:1}],name:'gj'})
db.stu.find({age:{$in:[18,28]}})
db.stu.find({name:/^黃/}) db.stu.find({name:{$regex:'^黃'}}})
db.stu.find({$where:function(){return this.age>20}})
db.集合名稱.find().limit(NUMBER)
db.stu.find().limit(2)
db.集合名稱.find().skip(NUMBER)
db.stu.find().skip(2)
方法limit()和skip()能夠一塊兒使用,不分前後順序sql
建立數據集 --for(i=0;i<15;i++){db.t1.insert({_id:i})}
mongodb
db.stu.find().limit(4).skip(5) 或 db.stu.find().skip(5).limit(4)
db.集合名稱.find({},{字段名稱:1,...})
db.stu.find({},{name:1,gender:1})
db.stu.find({},{_id:0,name:1,gender:1})
db.集合名稱.find().sort({字段:1,...})
db.stu.find().sort({gender:-1,age:1})
db.集合名稱.find({條件}).count()
db.集合名稱.count({條件})
db.stu.find({gender:1}).count()
db.stu.count({age:{$gt:20},gender:1})
db.集合名稱.distinct('去重字段',{條件})
db.stu.distinct('gender',{age:{$gt:18}})
db.集合名稱.aggregate([{管道:{表達式}}])
ps ajx | grep mongo
表達式:'$列名'
db.stu.aggregate([ {$group: { _id:'$gender', counter:{$sum:1} } } ])
db.stu.aggregate([ {$group: { _id:null, counter:{$sum:1}, avgAge:{$avg:'$age'} } } ])
db.stu.aggregate([ {$group: { _id:'$gender', name:{$push:'$name'} } } ])
db.stu.aggregate([ {$group: { _id:'$gender', name:{$push:'$$ROOT'} } } ])
db.stu.aggregate([ {$match:{age:{$gt:20}}} ])
db.stu.aggregate([ {$match:{age:{$gt:20}}}, {$group:{_id:'$gender',counter:{$sum:1}}} ])
db.stu.aggregate([ {$project:{_id:0,name:1,age:1}} ])
db.stu.aggregate([ {$group:{_id:'$gender',counter:{$sum:1}}}, {$project:{_id:0,counter:1}} ])
b.stu.aggregate([{$sort:{age:1}}])
db.stu.aggregate([ {$group:{_id:'$gender',counter:{$sum:1}}}, {$sort:{counter:-1}} ])
db.stu.aggregate([{$limit:2}])
db.stu.aggregate([{$skip:2}])
db.stu.aggregate([ {$group:{_id:'$gender',counter:{$sum:1}}}, {$sort:{counter:1}}, {$skip:1}, {$limit:1} ])
db.集合名稱.aggregate([{$unwind:'$字段名稱'}])
db.t2.insert({_id:1,item:'t-shirt',size:['S','M','L']})
db.t2.aggregate([{$unwind:'$size'}])
db.inventory.aggregate([{ $unwind:{ path:'$字段名稱', preserveNullAndEmptyArrays:<boolean>#防止數據丟失 } }])
db.t3.insert([ { "_id" : 1, "item" : "a", "size": [ "S", "M", "L"] }, { "_id" : 2, "item" : "b", "size" : [ ] }, { "_id" : 3, "item" : "c", "size": "M" }, { "_id" : 4, "item" : "d" }, { "_id" : 5, "item" : "e", "size" : null } ])
db.t3.aggregate([{$unwind:'$size'}])
db.t3.aggregate([{$unwind:{path:'$sizes',preserveNullAndEmptyArrays
#!/usr/bin/env python # -*- coding: utf-8 -*- import pymongo import datetime def get_db(): # 創建鏈接 client = pymongo.MongoClient(host="10.244.25.180", port=27017) db = client['example'] #或者 db = client.example return db def get_collection(db): # 選擇集合(mongo中collection和database都是延時建立的) coll = db['informations'] print db.collection_names() return coll def insert_one_doc(db): # 插入一個document coll = db['informations'] information = {"name": "quyang", "age": "25"} information_id = coll.insert(information) print information_id def insert_multi_docs(db): # 批量插入documents,插入一個數組 coll = db['informations'] information = [{"name": "xiaoming", "age": "25"}, {"name": "xiaoqiang", "age": "24"}] information_id = coll.insert(information) print information_id def get_one_doc(db): # 有就返回一個,沒有就返回None coll = db['informations'] print coll.find_one() # 返回第一條記錄 print coll.find_one({"name": "quyang"}) print coll.find_one({"name": "none"}) def get_one_by_id(db): # 經過objectid來查找一個doc coll = db['informations'] obj = coll.find_one() obj_id = obj["_id"] print "_id 爲ObjectId類型,obj_id:" + str(obj_id) print coll.find_one({"_id": obj_id}) # 須要注意這裏的obj_id是一個對象,不是一個str,使用str類型做爲_id的值沒法找到記錄 print "_id 爲str類型 " print coll.find_one({"_id": str(obj_id)}) # 能夠經過ObjectId方法把str轉成ObjectId類型 from bson.objectid import ObjectId print "_id 轉換成ObjectId類型" print coll.find_one({"_id": ObjectId(str(obj_id))}) def get_many_docs(db): # mongo中提供了過濾查找的方法,能夠經過各類條件篩選來獲取數據集,還能夠對數據進行計數,排序等處理 coll = db['informations'] #ASCENDING = 1 升序;DESCENDING = -1降序;default is ASCENDING for item in coll.find().sort("age", pymongo.DESCENDING): print item count = coll.count() print "集合中全部數據 %s個" % int(count) #條件查詢 count = coll.find({"name":"quyang"}).count() print "quyang: %s"%count def clear_all_datas(db): #清空一個集合中的全部數據 db["informations"].remove() if __name__ == '__main__': db = get_db() my_collection = get_collection(db) post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} # 插入記錄 my_collection.insert(post) insert_one_doc(db) # 條件查詢 print my_collection.find_one({"x": "10"}) # 查詢表中全部的數據 for iii in my_collection.find(): print iii print my_collection.count() my_collection.update({"author": "Mike"}, {"author": "quyang", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()}) for jjj in my_collection.find(): print jjj get_one_doc(db) get_one_by_id(db) get_many_docs(db) # clear_all_datas(db)