The Collection.add()
function is for storing
documents in a collection, similar to the
INSERT statement for an SQL
database. It takes a single document or a list of documents as
its argument, and is executed by the
execute()
function.
The collection needs to be created with the
Schema.createCollection()
function before
documents can be inserted. To insert documents into an existing
collection use the Schema.getCollection()
function to retrieve the Collection object.
The following example shows how to use the
Collection.add()
function. The example
assumes that the test schema exists and that the collection
my_collection
does not exist.
MySQL Shell JavaScript Code
// 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();
MySQL Shell Python Code
# Create a new collection
myColl = db.create_collection('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()
Node.js JavaScript Code
// Create a new collection
db.createCollection('myCollection').then(function (myColl) {
return Promise.all([
// 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()
])
});
C# Code
// Assumptions: test schema assigned to db, my_collection collection not exists
// Create a new collection
var myColl = db.CreateCollection("my_collection");
// Insert a document
myColl.Add(new { name = "Laurie", age = 19 }).Execute();
// Insert several documents at once
myColl.Add(new[] {
new { name = "Nadya", age = 54 },
new { name = "Lukas", age = 32 } }).Execute();
Python Code
# Create a new collection
my_coll = my_schema.create_collection('my_collection')
# Insert a document
my_coll.add({ 'name': 'Laurie', 'age': 19 }).execute()
# Insert several documents at once
my_coll.add([
{ 'name': 'Nadya', 'age': 54 },
{ 'name': 'Lukas', 'age': 32 }
]).execute()
Java Code
// Create a new collection
Collection coll = db.createCollection("payments");
// Insert a document
coll.add("{ \"name\":\"Laurie\", \"age\":19 }").execute();
// Insert several documents at once
coll.add("{ \"name\":\"Nadya\", \"age\":54 }",
"{ \"name\":\"Lukas\", \"age\":32 }").execute();
C++ Code
// Create a new collection
Collection coll = db.createCollection("payments");
// Insert a document
coll.add(R"({ "name":"Laurie", "age":19 })").execute();
// Insert several documents at once
std::list<DbDoc> docs = {
DbDoc(R"({ "name":"Nadya", "age":54 })"),
DbDoc(R"({ "name":"Lukas", "age":32 })")
};
coll.add(docs).execute();
See also CollectionAddFunction for
the syntax of add()
in EBNF.