Documentation Home
X DevAPI User Guide for MySQL Shell in JavaScript Mode
Download this Manual
PDF (US Ltr) - 1.2Mb
PDF (A4) - 1.2Mb


5.1 Creating Documents

Once a collection has been created, it can store JSON documents. You store documents by passing a JSON data structure to the Collection.add() function. Some languages have direct support for JSON data, others have an equivalent syntax to represent that data. MySQL Connectors that implement X DevAPI aim to implement support for all JSON methods that are native to the Connectors' specific languages.

In addition, in some MySQL Connectors the generic DbDoc objects can be used. The most convenient way to create them is by calling the Collection.newDoc(). DbDoc is a data type to represent JSON documents and how it is implemented is not defined by X DevAPI. Languages implementing X DevAPI are free to follow an object-oriented approach with getter and setter methods, or use a C struct style with public members.

For strictly-typed languages it is possible to create class files based on the document structure definition of collections. MySQL Shell can be used to create those files.

Table 5.1 Different Types of Document Objects, Their Supported Languages, and Their Advantages

Document Objects

Supported languages

Advantages

Native JSON

Scripting languages (JavaScript, Python)

Easy to use

JSON equivalent syntax

C# (Anonymous Types, ExpandoObject)

Easy to use

DbDoc

All languages

Unified across languages

Generated Doc Classes

Strictly typed languages (C#)

Natural to use


The following example shows the different methods of inserting documents into a collection.

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

// Insert JSON data directly
myColl.add({_id: '8901', name: 'Mats', age: 21}).execute();

// Inserting several docs at once
myColl.add([ {_id: '8902', name: 'Lotte', age: 24},
  {_id: '8903', name: 'Vera', age: 39} ]).execute();