創建集合 新建集合 點擊保存 給集合起名字 創建一個查詢 新增 -- 新增數據2種方式 db.mongodb_test.save({"name":"stringBoot"}) db.mongodb_test.insert({"name":"mango good"}); db.mongodb_test ...
創建集合
新建集合


新增
-- 新增數據2種方式

查詢
-- 查詢所有數據2種寫法
db.mongodb_test.find() //查詢全部 相當於:select* from user;

-- 查詢去掉後的當前聚集集合中的某列的重覆數據
db.mongodb_test.distinct("name") //會過濾掉 name 中的相同數據 相當於:select distict name from user;

-- 查詢 age = 17 的記錄
db.mongodb_test.find({"age":17}) //相當於: select * from user where age = 22;

-- 查詢 age > 22 的記錄
db.mongodb_test.find({"age":{$gt:17}}) // select * from user where age >22;

-- 查詢 age < 18 的記錄
db.mongodb_test.find({"age":{$lt:18}}) // select * from user where age <18;


-- 查詢 name 中包含 string 的數據 模糊查詢用於搜索
-- 查詢 name 中包含 mongo 的數據 模糊查詢用於搜索 db.mongodb_test.find({"name":/string/}) //select * from user where name like ‘%string%’;

-- 查詢 name 中以 ad 開頭的
db.mongodb_test.find({"name":/^ad/}) //select * from user where name like ‘mongo%’;

-- 查詢 name 中以 ing 結尾的
db.mongodb_test.find({"name":/ing$/}) //SELECT * FROM car WHERE car.type like '%ing'

-- 查詢指定列 name、age 數據
name 也可以用 true 或 false,當用 ture 的情況下和 name:1 效果一樣, 如果用 false 就是排除 name,顯示 name 以外的列信息。 db.mongodb_test.find( //select name, age from user; {}, {"name":1,"age":1} )

--查詢指定列 name、age 數據, age > 25
db.mongodb_test.find( //select name, age from user where age >25; {"age":{$gt:17}}, {"name":1,"age":1} )

-- 按照年齡排序 1 升序 -1 降序
db.mongodb_test.find().sort({"age":1})

-- 按照年齡排序 1 升序 -1 降序
db.mongodb_test.find().sort({"age":-1})

-- 查詢 name = String, age = 18 的數據
db.mongodb_test.find({"name":"string","age":18}) //select * from user where name = ‘String’ and age = ‘18’;

-- 查詢 2 條以後的數據
db.mongodb_test.find().skip(2)

-- 查詢在 1-3 之間的數據
可用於分頁,limit 是 pageSize,skip 是 (page-1) * pageSize db.mongodb_test.find().limit(1).skip(3)

-- or 或 查詢
db.mongodb_test.find( //select * from user where age = 22 or age = 25; {$or:[ {"age":17}, {"age":16} ]} )

-- findOne 查詢第一條數據
db.mongodb_test.findOne() // selecttop 1 * from user; db.user.find().limit(1);

-- 查詢某個結果集的記錄條數 統計數量
db.mongodb_test.find({"age":{$gte:17}}).count()

修改數據
--修改裡面還有查詢條件。你要該誰,要告訴 mongo。-- 查找名字叫做小明的,把年齡更改為 16 歲:
db.mongodb_test.update({"name":"string"},{$set:{"sex":"男"}})

-- 查找名字叫做string的,把年齡更改為 22 歲:
db.mongodb_test.update({"name":"string"},{$set:{"age":22}})

-- 查找數學年齡是 22,把年齡更改為 33 歲 性別改為女:
db.mongodb_test.update({"age":22},{$set:{"age":33,"sex":"女"}});

-- $inc修改器
-- 比如我們做一個線上用戶狀態記錄,每次修改會在原有的基礎上自增$inc指定的值,如果“文檔”中沒有此key,則會創建key db.mongodb_test.update({"name":"string"},{$inc:{"age":50}},false,true) //:update users set age = age + 50 where name = ‘Lisi’;


-- 註意:不寫 $set 關鍵字,則完整替換整條數據
db.mongodb_test.update({"name":"string"},{"name":"stringOne"})


刪除
-- 刪除指定的數據
db.collectionsNames.remove({"key":"val"}) eg: db.mongodb_test.remove({"age":{$gt:11}})


-- 預設情況下,remove()方法會刪除所有符合 remove 條件的文檔。
使用 justOne 選項將刪除操作限製為僅對一個匹配文檔執行。 db.mongodb_test.remove({"age":{$gt:11}},{justOne:true})

