例如:現(xiàn)在有數(shù)據(jù)庫
node_club_dev
表(集合)
messages
node_club_dev
topiccollects
topics
users
col
1.創(chuàng)建數(shù)據(jù)庫
use node_club_dev
如果數(shù)據(jù)庫不存在逞怨,則創(chuàng)建數(shù)據(jù)庫,否則切換到指定數(shù)據(jù)庫泡仗。
db
顯示當前數(shù)據(jù)
show dbs
顯示所有數(shù)據(jù)庫
2. 刪除數(shù)據(jù)庫node_club_dev
user node_club_dev
db.dropDatabase()
返回 { "dropped" : "node_club_dev", "ok" : 1 }
刪除表(集合)
user node_club_dev
show tables
db.messages.drop() //刪除node_club_dev里的表messages
3.插入表數(shù)據(jù)
1
db.messages.insert({"title":"標題", "desrpert":"這是描述"})
2
db.messages.insert({title:'MongoDb', description:'MongoDB是一個Nosql數(shù)據(jù)庫', by:'Mongodb 基本使用教程', url:'http://www.baidu.com', tags:['mongodb','databse', 'Nosql'],likes:100})
4.查找
db.messages.find() //所有的
4查找的數(shù)據(jù)格式化輸出
db.messages.find().pretty()
5.更新標題
db.messages.update({'title':'MongoDb'},{$set:{'title':'MongoDB更新'}})
更多實例
只更新第一條記錄:
db.messages.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );
全部更新:
db.messages.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );
只添加第一條:
db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );
全部添加加進去:
db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );
全部更新:
db.messages.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );
只更新第一條記錄:
db.messages.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );
4.刪除記錄(文檔)
db.messages.remove({'title':'MongoDb教程'})
刪除所有
db.messages.remove({})
5.查找
mondb sql
db.col.find({"by":"菜鳥教程"}).pretty() where by = '菜鳥教程'
db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
and 類查找
db.col.find({"by":"菜鳥教程", "title":"MongoDB 教程"}).pretty()
or 類查找
db.col.find({$or:[{"by":"菜鳥教程"},{"title": "MongoDB 教程"}]}).pretty()
AND 和 OR 聯(lián)合使用
db.col.find({"likes": {$gt:50}, $or: [{"by": "菜鳥教程"},{"title": "MongoDB 教程"}]}).pretty()
'where likes>50 AND (by = '菜鳥教程' OR title = 'MongoDB 教程')'
$gt -------- greater than
$gte --------- gt equal
$lt -------- less than
$lte --------- lt equal
$ne ----------- not equal
獲取"col"集合中 "likes" 大于100索赏,小于 200 的數(shù)據(jù)
db.col.find({likes : {$lt :200, $gt : 100}})
col 集合中的數(shù)據(jù)按字段 likes 的降序排列
db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
6 索引
db.col.ensureIndex({"title":1})
7.聚合
·