PDF (美國信紙尺寸) - 1.4Mb
PDF (A4) - 1.4Mb
為了擷取資料庫中現有集合的集合物件,請從綱要物件呼叫 getCollection()
函數。
如果集合在資料庫中尚不存在,後續任何呼叫集合物件函數都會擲回錯誤;對於某些連接器,您可以透過將 validateExistence
欄位設定為 true 並將其作為第二個參數傳遞給 db.getCollection()
,來避免這種情況,並在擷取集合時立即捕捉錯誤。
MySQL Shell JavaScript 程式碼
// Get a collection object for 'my_collection'
var myColl = db.getCollection('my_collection');
MySQL Shell Python 程式碼
# Get a collection object for 'my_collection'
myColl = db.get_collection('my_collection')
Node.js JavaScript 程式碼
// Get a collection object for 'my_collection'
var collection = db.getCollection('my_collection');
C# 程式碼
// Get a collection object for "my_collection"
var myColl = db.GetCollection("my_collection");
// Get a collection object but also ensure it exists in the database
var myColl2 = db.GetCollection("my_collection", ValidateExistence: true);
Python 程式碼
# Get a collection object for 'my_collection'
my_coll = my_schema.get_collection('my_collection')
# Get a collection object but also ensure it exists in the database
my_coll = my_schema.get_collection('my_collection', True)
Java 程式碼
// Get a collection object for 'my_collection'
Collection myColl = db.getCollection("my_collection");
// Get a collection object but also ensure it exists in the database
// Second parameter is: boolean requireExists
Collection myColl = db.getCollection("my_collection", true);
C++ 程式碼
// Get a collection object for 'my_collection'
Collection myColl = db.getCollection("my_collection");
// Get a collection object but also ensure it exists in the database
Collection myColl = db.getCollection("my_collection", true);
createCollection()
與設定為 true 的 ReuseExistingObject
欄位一起使用,可用於建立新的集合或重複使用具有給定名稱的現有集合。請參閱第 4.2.1 節「建立集合」以取得詳細資訊。
注意
在大多數情況下,最好在開發期間建立資料庫物件,並避免在資料庫專案的生產階段動態建立它們。因此,最好將在資料庫中建立集合的程式碼與實際的使用者應用程式碼分開。