1. 程式人生 > 其它 >MongoDB 集合(collection)常用方法 (Method)

MongoDB 集合(collection)常用方法 (Method)

collection 的官方 method文件

db.collection.aggregate():
對集合進行聚合操作

db.collection.countDocuments(query, limit, skip, ...):
返回滿足條件的文件數

db.collection.createIndex(keys, background,unique,name,...)
為集合建立新的索引

db.collection.dataSize():返回集合的位元組數

db.collection.deleteOne(query):
刪除滿足條件的第一個文件

db.collection.deleteMany(query)

:
刪除滿足條件的所有文件

db.collection.drop()
刪除該集合及相關的索引等檔案

db.collection.dropIndex(index)
刪除指定的索引

db.collection.dropIndexes(index)
刪除指定的多個索引

db.collection.deleteOne(filter,...)
刪除滿足條件的第一個文件

db.collection.deleteMany(filter,...):
刪除滿足條件的所有文件

db.collection.explain()
和其他方法一起使用,用於輸出具體的執行過程

db.collection.find(query, projection)

  • query:用於指定過濾條件;
  • projection:用於投影欄位;
  • 返回滿足條件的所有文件

db.collection.findOne(query, projection)
返回滿足條件的第一個文件

db.collection.findAndModify(query,sort,remove,document,upsert,...)
upsert設定為true時,當沒有滿足條件的文件時,文件將插入集合

db.collection.getIndexes()
返回該集合的所有索引

db.collection.insert(document)
db.collection.insertOne(document)


db.collection.insertMany(documents)
向集合中插入一個或多個文件

db.collection.isCapped()
判斷該集合是否是固定集合

db.collection.reIndex()
刪除該集合所有的索引,並重新建立(執行期間無法執行其他指令)

db.collection.remove(query, justOne):
刪除該集合中滿足條件的文件

db.collection.renameCollection(newName)
更改集合名稱

db.collection.replaceOne(filter, replacement,{upsert,...})
替換符合條件的文件

db.collection.save(document)
更新現有集合

db.collection.stats({scale,indexDetails,...}):
返回該集合的統計資訊

db.collection.storageSize()
返回該集合文件的總儲存空間

db.collection.totalSize()
返回該集合文件和索引所佔的總位元組數

db.collection.update(query, update, {upsert,multi,...})
multi:設定為true,更新所有滿足條件的文件,預設只更新第一個文件

db.collection.updateOne(filter, update, options)
db.collection.updateMany(filter, update, options)
更新滿足條件的一個或多個文件

棄用的方法(method)

db.collection.count() 建議使用db.collection.countDocuments()代替
db.collection.ensureIndex(): 建議使用db.collection.createIndex()代替