CRUD操作即對文檔進行create,read,update 和 update 。
創建(create)操作
創建或者插入都是添加一個新的文檔(document)到集合(collection)中。如果集合不存在,插入操作將創建該集合。
MongoDB提供下面的方法將一個文檔插入到集合中:
db.collection.insertOne({})
db.collection.insertMany([{},{}])
(在3.4.4版本中,如果一開始打開shell,并沒有use某個數據庫,會默認使用test數據庫,如果該數據庫不存在,則創建。在某個數據庫下,插入時,如果沒有該collection,則創建)。
在MongoDB中,插入操作把集合作為目標。對于一個文檔而言,所有的寫入操作都是原子的(atomic)(An atomic operation in a database is an undividable and complex series of database operations such that either all operation will occur, or nothing will occur. The term atomicity is used to guarantee that there will be no partial database update )。
讀操作
讀操作就是從collection中索引document。MongoDB提供了下面的方法進行讀取:
db.collection.find()
你可以指定選擇器來確認要返回的document。
更新操作
更新操作就是編輯修改collection中已經存在的document。MongoDB提供了下面的方法來完成update操作:
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
在MongoDB中,更新操作的目標是一個單獨的collection。所有的寫操作在MongDB的document層級上是原子的。
你可以指定標準或者過濾器來確認要update的document。
刪除操作
刪除操作就是從collection中刪除document。MongoDB提供下面的方法完成刪除:
db.collection.deleteOne()
db.collection.deleteMany()
在MongoDB中,刪除操作是針對一個單獨的collection,所有的寫入操作在MongoDB的document層級上,都是原子的。
你可以指定標準,或者過濾器來確定要刪除的document。