4.3.1 Collection.add()

Collection.add() 函數用於在集合中儲存文件,類似於 SQL 資料庫的 INSERT 陳述式。它會將單一文件或文件清單作為其引數,並由 execute() 函數執行。

必須先使用 Schema.createCollection() 函數建立集合,才能插入文件。若要將文件插入現有的集合中,請使用 Schema.getCollection() 函數來擷取集合物件。

以下範例顯示如何使用 Collection.add() 函數。此範例假設測試綱要存在,且集合 my_collection 不存在。

// Create a new collection
var myColl = db.createCollection('my_collection');

// Insert a document
myColl.add({ name: 'Laurie', age: 19 }).execute();

// Insert several documents at once
myColl.add([
{ name: 'Nadya', age: 54 },
{ name: 'Lukas', age: 32 } ]).execute();

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