Documentation Home
X DevAPI User Guide
Download this Manual

X DevAPI User Guide  /  ...  /  Working with Existing Collections

4.2.2 Working with Existing Collections

In order to retrieve a Collection object for an existing collection stored in the database call the getCollection() function from a Schema object.

MySQL Shell JavaScript Code

// Get a collection object for 'my_collection'
var myColl = db.getCollection('my_collection');

MySQL Shell Python Code

# Get a collection object for 'my_collection'
myColl = db.get_collection('my_collection')

Node.js JavaScript Code

// Get a collection object for 'my_collection'
var collection = db.getCollection('my_collection');

C# Code

// 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 Code

# Get a collection object for 'my_collection'
my_coll = my_schema.get_collection('my_collection')

Java Code

// 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++ Code

// 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);

If the collection does not yet exist in the database any subsequent call of a Collection object function throws an error. To prevent this and catch the error right away set the validateExistence field to true and pass it as second parameter to db.getCollection().

The createCollection() together with the ReuseExistingObject field set to true can be used to create a new or reuse an existing collection with the given name.

Note

In most cases it is good practice to create database objects during development time and refrain from creating them on the fly during the production phase of a database project. Therefore it is best to separate the code that creates the collections in the database from the actual user application code.


User Comments
User comments in this section are, as the name implies, provided by MySQL users. The MySQL documentation team is not responsible for, nor do they endorse, any of the information provided here.
Sign Up Login You must be logged in to post a comment.