MongoDB簡介
- 基于分布式檔案存盤的開源資料庫系統
- 將資料存盤為一個檔案,檔案類似于Json格式
MongoDB進入與退出
- 進入:mongo
- 退出:exit
庫級操作
- 顯示所有庫: show dbs
- 切換/創建資料庫: use 資料庫名稱
- 查看所在庫: db
- 洗掉庫:db.dropDatabase() -- 切換到要洗掉的資料庫里進行洗掉
集合操作
- 顯示當前資料庫的集合: show collections
- 創建集合: db.createCollection( '集合名稱' )
- 洗掉集合: db.集合名稱.drop() -- 回傳 true 或 false
檔案操作
添加檔案(資料) ??? db.集合名稱.insert(document)
- 每一條資料,就是一個document,就是一條json
- 添加檔案時,如果不指定_id引數,MongoDB會為檔案分配一個唯一的ObjectId
- 例: db.student.insert({'_id':1, name:'xiaoming', age:18})
- 添加多條檔案
- 例: db.student.insert( [ { } , { } , ... ] )
- 例: db.student.insert( [ { } , { } , ... ] )
洗掉檔案(資料) ??? db.集合名稱.remove(<query>, {justOne:})
- 洗掉集合中所有的檔案:db.table.remove( {} )
- 洗掉集合中滿足條件的所有檔案:db.table.remove({sex: '男'})
- 只洗掉集合中滿足條件的第一條檔案: { justOne: true }
- 例: db.table.remove({sex:'男'}, { justOne:true} )
- 例: db.table.remove({sex:'男'}, { justOne:true} )
修改檔案(資料) ??? db.集合名稱.update(<query>, <update>, {multi:<boolean>})
- 修改一條資料: db.table.update({name:'xiaoming'}, {age:20})--(只有age,沒有name了,整條資料變成<update>里的內容)
- 指定屬性修改: { $set: {age:20} }
- 例: db.table.update({name:'xiaoming'}, {$set: {age:666, sex: 'xx'}} )
- 更新集合中所有滿足條件的檔案: { multi: true }
- 例: db.table.update({sex:'男'}, {$set:{sex:'女'}}, { multi:true} )
- 例: db.table.update({sex:'男'}, {$set:{sex:'女'}}, { multi:true} )
查詢檔案(資料) ??? db.集合名稱.find([conditions])
- 查看集合中全部資料: db.student.find()
- 格式化顯示: db.student.find().pretty()
- 查看滿足條件的資料: db.student.find({name:'xiaoming'})
簡單條件
- and條件
- {$and:[{expression1}, {expression1}, ...] }
- or條件
- { $or : [ { } , { }, ...] }
- and和or混用
- db.table.find( {$or:[ {$and:[{sex:'女'}, {age:18}]} , {$and:[{sex:'男'}, {age:{$gt:18}}]} ] } )
- db.table.find( { $or : [ { $and:[ { } , { } ] } , { $and:[ { } , { } ] } ] } )
- 運算子
- $ne:不等于
- $gt :大于
- $lt :小于
- $gte:大于等于
- $lte :小于等于
- 例:db.user.find( { 'age' : {'$ne': 45 } } )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/29444.html
標籤:NoSQL
