列出資料庫:show dbs
切換資料庫(如果不存在則自動建立):use dbname
檢視目前資料庫:db
列出集合:show collections 或者 show tables
删除資料庫:切換到要删除的資料庫下執行:db.dropDatabase()
建立集合,在插入資料時,如果集合不存在,則會自動建立集合。
插入資料:db.gooverit_collection.insert({x:1}) 或者 db.gooverit_collection.save({x:2})
批量插入資料:for(i=3;i<=100;i++)db.gooverit_collection1.insert({x:i})
統計文檔數:db.gooverit_collection1.count()
查詢(檢視集合的文檔清單):db.gooverit_collection1.find()
輸入 it 可以檢視更多。
查詢指定條件的文檔:db.gooverit_collection1.find({x:1})
MongoDB中條件操作符有: 大于 - $gt 小于 - $lt 大于等于 - $gte 小于等于 - $lte db.gooverit_collection1.find({x:{$gt:98}})
db.gooverit_collection1.find({x:{$gt:98,$lt:1000}})
資料更新:
db.collection.update( criteria, objNew, upsert, multi ) update()函數接受以下四個參數: criteria : update的查詢條件,類似sql update查詢内where後面的。 objNew : update的對象和一些更新的操作符(如$,$inc...)等,也可以了解為sql update查詢内set後面的 upsert : 這個參數的意思是,如果不存在update的記錄,是否插入objNew,true為插入,預設是false,不插入。 multi : mongodb預設是false,隻更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
db.gooverit_collection1.update({x:1},{x:1000})
移除: 移除指定文檔:db.gooverit_collection1.remove({x:1}) 移除所有文檔:db.gooverit_collection1.remove({}) 移除指定集合:db.gooverit_collection1.drop()
分頁: skip()跳過指定數量的資料 limit()指定讀取的記錄條數。 db.gooverit_collection1.find().skip(10).limit(5)
排序: sort()指定排序的字段,并使用 1 和 -1 來指定排序的方式,其中 1 為升序排序,而-1是用于降序排列。
db.gooverit_collection1.find().skip(10).limit(5).sort({x:1}) db.gooverit_collection1.find().skip(10).limit(5).sort({x:-1})