mongodb基本知識

來源: https://www.runoob.com/mongodb/mongodb-tutorial.html
簡要說明:

sql術語 mongodb術語 解釋說明
database database 數據庫
table collection 數據庫表/集合
row document 數據記錄行/文檔
column field 數據字段/域
index index 索引
primary key _id 主鍵

兩者不同的特點之一,:
mongodb文檔(document)的域(field)是動態的,域個數量可以不同, 保存值類型可以任意
而數據庫表(table)每行(row)的字段(column)是固定的, 既每row的column數量一直,且column保存類型是固定的.

mongodb基本命令:

 show dbs             # 查看數據庫: 
 use test             # 使用數據庫 注: 使用test數據庫, 沒有的話自動創建
 db.dropDatabase()    # 刪除數據庫:

db.createCollection("db_test")          # 創建集合         
show collections                        # 查詢集合         
db.db_test.insert({"name":"luck_hwb"})  # 插入文檔   注: sql中的insert 文檔就是json對象
-- 查詢 begin--
db.db_test.find()                          # 查詢文檔 注: sql中的select
db.db_test.find().limit(2)                 # 查詢文檔個數   注: sql中的limit 0,2
db.db_test.find().limit(2).skip(1)         # 查詢文檔區間   注: sql中的limit 1,2
db.db_test.find().sort({"_id":1})          # 排序(1:正序,-1倒序)
db.db_test.find().pretty()                 # 查詢文檔 格式化輸入
-- 查詢 end--
db.db_test.update({"name":"luck_hwb"},{$set:{"age":"18"}})                     # 更新文檔   注: sql中的update
db.db_test.save({"_id":ObjectId("5dbbe0ba194429cb33531ed6"),"name":"new_obj"}) # 插入/替換文檔
db.db_test.remove({"name":"new_obj"})      # 刪除文檔 sql中的delete
--條件查詢文檔 begin--
db.db_test.find({$or:[{"name":"luck_hwb"},{"name":"new_obj"}]}).pretty()   -> where  name = 'luck_hwb' or  name = 'new_obj'
db.db_test.find({"age":{$gt:5}})           -> where  age > 5
db.db_test.find({"age":{$gte:5}})          -> where  age >= 5
db.db_test.find({"age":{$gte:5}})          -> where  age >= 5
db.db_test.find({"age":{$gt:4,$lt:6}})     -> where  age > 4 and age < 6
--條件查詢文檔 end--
--統計 begin--
db.db_test.aggregate([{$group:{_id:null, num_tutorial:{$sum:1}}}])            -> select sum(1) from db_test 
db.db_test.aggregate([{$group:{_id:"$user_id", num_tutorial:{$sum:"$age"}}}]) -> select user_id, sum(age)  from db_test group by user_id
--統計 end--

db.db_test.createIndex({"name":1})       # 創建索引(1:升序創建索引, -1:降序創建索引)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章