文件首頁
X DevAPI 使用者指南
下載本手冊
PDF (美式信紙) - 1.4Mb
PDF (A4) - 1.4Mb


X DevAPI 使用者指南  /  ...  /  Collection.remove()

4.3.4 Collection.remove()

Collection.remove() 函數用於移除集合中的文件,類似於 SQL 資料庫的 DELETE 陳述式。它會採用搜尋條件字串 (SearchConditionStr) 作為參數,以指定應從集合中移除的文件(關於 SearchConditionStr 的詳細說明,請參閱 第 4.3.2 節,「Collection.find()」)。如果未提供搜尋條件字串,或如果提供的字串為空字串,remove() 會傳回錯誤。如果傳入任何評估結果為 true 但未比對任何文件的運算式(例如,「true」或「_id IS NOT NULL」)作為搜尋條件字串,則會移除集合中的所有文件。

以下方法可以鏈結至 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() 函數。它假設已將一些文件新增至集合,如 第 4.3.1 節,「Collection.add()」中的程式碼範例所示

MySQL Shell JavaScript 程式碼

// Use the collection 'my_collection'
var myColl = db.getCollection('my_collection');

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

MySQL Shell Python 程式碼

# 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()

Node.js JavaScript 程式碼

// Use the collection 'my_collection'
var myColl = db.getCollection('my_collection');

// Remove documents by criteria
myColl
  .remove('name like :name && age < :age')
  .limit(1)
  .bind({ name: 'N%', age: 60 })
  .execute();

C# 程式碼

// Use the collection "my_collection"
var myColl = db.GetCollection("my_collection");

// Remove documents by criteria
myColl.Remove("name like :name AND age < :age").Limit(1).Bind("name","N%").Bind("age", 60).Execute();

Python 程式碼

# Use the collection "my_collection"
my_coll = my_schema.get_collection('my_collection')

# Remove documents by criteria
my_coll.remove("name like :name AND age < :age").limit(1).bind("name","N%").bind("age", 60).execute();

Java 程式碼

// Use the collection 'my_collection'
Collection myColl = db.getCollection("my_collection");

// Remove documents by criteria 
myColl.remove("name like :name AND age < :age").limit(1)
  .bind("name","N%").bind("age", 60).execute();

C++ 程式碼

// Use the collection 'my_collection'
Collection myColl = db.getCollection("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() 的語法。