《左手MongoDB右手Redis》第3章笔记-robo3t上进行增删改查
表3-1 SQL與MongoDB術語對比
無論是插入一條數據還是插入多條數據,每一條數據被插入
MongoDB 后都會被自動添加一個字段“_id”。“_id”讀作“Object Id”,它
是由時間、機器碼、進程pid和自增計數器構成的。
“_id”始終遞增,但絕不重復。
● 同一時間,不同機器上面的“_id”不同。
● 同一機器,不同時間的“_id”也不同。
● 同一機器同一時間批量插入的數據,“_id”依然不同。
#---------------------------------------------robo3t操作-------------------------------------
robo3t創建數據庫:
?
創建集合:
?
插入單條數據:
db.getCollection('example_data_1').insertOne({"name": "張小二 ", "age": 17,"address": "浙江"})
JSON字符串必須使用雙引號,不過這個規定在MongoDB中并非強制性的,用單引號也沒有問題。
db.getCollection("example_data_1").insertOne({"name":"王小六", "age": 25, "work":"廚師"})
插入后效果如下:
?
db.getCollection("example_data_1").insertOne({"hello":"world","sex":"男","職位":"工程師"})
db.getCollection("example_data_1").insertOne({"name":18030,"age":"十歲","address":3.5})
db.getCollection("example_data_1").insertMany([
{"name":"朱小三","age":20,"address":"北京"},
{"name":"劉小四","age":21,"address":"上海"},
{"name":"馬小五","age":22,"address":"山東"},
{"name":"夏侯小七","age":23,"address":"河北"},
{"name":"公孫小八","age":24,"address":"廣州"},
{"name":"慕容小久","age":25,"address":"杭州"},
{"name":"歐陽小十","age":26,"address":"深圳"},
])
?
| 任務 | mongodb 代碼 |
| 查詢所有數據 | db.getCollection('example_data_1').find({'age': 25}) |
| 查詢特定數據 | db.getCollection("example_data_1").find({"age":25,"name":"慕容小九"}) |
| 查詢范圍值數據 | db.getCollection('example_data_1').find({'age': {'$gte': 25}}) |
| 查詢所有“age”大于21并小于等于24的數據。 | db.getCollection('example_data_1').find({'age': {'$lt': 25, '$gt': 21}}) |
| 查詢所有“age”大于21并小于等于24的數據,且“name”不 為“夏侯小七”的記錄 | db.getCollection("example_data_1").find({ "age":{ "$lt":25, "$gt":21, }, "name":{"$ne":"夏侯小七"}}) |
| 限定返回哪些字段 | db.getCollection('example_data_1').find({}, {'address': 0, 'age': 0}) |
| 滿足要求的數據有多少條 | db.getCollection('example_data_1').find({'age': {'$gt': 21}}).count() |
| 限定返回結果——“limit()”命令 | db.getCollection('example_data_1').find().limit(4) |
| 對查詢結果進行排序——“sort()”命令 | db.getCollection('example_data_1').find({'age': {'$gt': 21}}).sort({'age': -1}) |
| 更新集合中的單條數據 | db.getCollection("example_data_1").updateMany( {"name":"王小六"}, {"$set":{"address":"蘇州","work":"工程師"}} ) |
| 查詢字段“hello”中值為“world”的這一條記錄 | db.getCollection('example_data_1').find({'hello': 'world'}) |
| 刪 除所有滿足要求的數據 | db.getCollection('example_data_1').deleteMany({'hello': 'world'}) |
| 對“age”字段去重 | db.getCollection('example_data_1').distinct('age') |
| 對“age”大于等于24的記錄的“age”字段去重 | db.getCollection("example_data_1").distinct( "age", {"age":{"$gte":24}} ) |
慎用刪除功能。一般工程上會使用“假刪除”,即:在文檔里面
增加一個字段“deleted”,如果值為0則表示沒有刪除,如果值為1則
表示已經被刪除了。
默認情況下,deleted字段的值都是0,如需要執行刪除操作,則
把這個字段的值更新為1。而查詢數據時,只查詢deleted為0的數據。
這樣就實現了和刪除一樣的效果,即使誤操作了也可以輕易恢復
?
總結
以上是生活随笔為你收集整理的《左手MongoDB右手Redis》第3章笔记-robo3t上进行增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 番茄小说app如何手动对换钱(好看的小说
- 下一篇: 梦幻西游保释金怎么退