下載本手冊
PDF (美式信紙) - 1.2Mb
PDF (A4) - 1.2Mb


4.3.4 Collection.remove()

Collection.remove() 函式用於移除 collection 中的文件,類似於 SQL 資料庫的 DELETE 語句。它採用搜尋條件字串 (SearchConditionStr) 作為參數,以指定應從 collection 中移除的文件(SearchConditionStr 的詳細說明可在 第 4.3.2 節,「Collection.find()」中找到)。如果未提供搜尋條件字串,或提供空字串,remove() 會傳回錯誤。如果傳遞的搜尋條件字串評估為 true 且沒有符合任何文件 (例如,「true」或「_id IS NOT NULL」),則會移除 collection 中的所有文件。

以下方法可以鏈結至 remove() 方法以配置刪除作業

  • limit(int):將要刪除的文件數限制為 int

  • sort(sortCriteriaList):根據 sortCriteriaList 對要刪除的文件排序,sortCriteriaList 是以逗號分隔的清單或 sortCriteria 的陣列。每個 sortCriteria 由元件名稱和搜尋順序 (asc 為遞增,或 desc 為遞減) 組成。例如

    • sort('name asc', 'age desc')

    • sort(['name asc', 'age desc'])

    此方法通常與 limit() 方法結合使用,以決定符合搜尋條件字串的哪些文件要刪除。

也支援使用 bind() 的參數繫結,而 execute() 函式會觸發實際的移除操作執行。以下範例顯示如何使用 Collection.remove() 函式。它假設已將一些文件新增至 collection,如第 4.3.1 節,「Collection.add()」中的程式碼範例所示

# Use the collection 'my_collection'
myColl = db.get_collection('my_collection')

# Remove documents by criteria
myColl.remove('name like :name AND age < :age') \
  .limit(1).bind('name','N%').bind('age', 60).execute()

另請參閱 CollectionRemoveFunction 以了解 EBNF 中 add() 的語法。