Bulk writes
This guide covers common patterns for bulk writes in FQL. You use bulk writes to create, update, or delete multiple collection documents in a single transaction.
Create multiple documents
// Create an array of objects that contain document data.
let customers = [
{ firstName: "Ruby", lastName: "Von Rails", email: "ruby@example.com" },
{ firstName: "Scott", lastName: "Chegg", email: "chegg@example.com" },
{ firstName: "Hilary", lastName: "Ouse", email: "ouse@example.com" }
]
// Use `forEach()` to create a `Customer` collection document for each
// element of the previous array.
customers.forEach(doc => Customer.create({ doc }))
// `forEach()` returns `null`.
Reference: forEach() ,
create() |
---|
Edit multiple documents
// Get a set of `Customer` collection documents with an
// `address` in the `state` of `DC`.
let customers = Customer.where( .address?.state == "DC" )
// Use `forEach()` to update each document in the previous set.
customers.forEach(doc => doc.update({
address: {
state: "District of Columbia"
}
})) // `forEach()` returns `null`.
Reference: forEach() ,
update() |
---|
Delete multiple documents
// Get a set of `Customer` collection documents with an
// `address` in the `state` of `DC`.
let customers = Customer.where( .address?.state == "DC" )
// Use `forEach()` to delete each document in the previous set.
customers.forEach(doc => doc.delete())
// `forEach()` returns `null`.
Reference: forEach() ,
delete() |
---|
Paginate bulk writes
Transactions are subject to size limits.
If you’re performing bulk writes on a large dataset, you can use
pageSize()
and
paginate()
to perform the
write over several transactions instead of one.
// Get a set of `Customer` collection documents with an
// `address` in the `state` of `DC`. Use `pageSize()`
// and`paginate()` to paginate results and
// limit each page to two documents.
let page = Customer.where( .address?.state == "DC" )
.pageSize(2).paginate()
// `paginate()` returns an object. The object's `data` property
// contains an array of `Customer` documents.
let data = page.data
// Use `forEach()` to update each `Customer` document in the
// `data` array.
data.forEach(doc => doc.update({
address: {
state: "District of Columbia"
}
}))
// Project the `after` cursor returned by `paginate()`.
// You can use the cursor to iterate through the remaining
// pages.
page {
after
}
The query returns an after
cursor:
{
after: "hdWDxoq..."
}
Subsequent transactions use the cursor and
Set.paginate()
to iterate
through the remaining pages:
// Uses `Set.paginate()` to iterate through pages.
let page = Set.paginate("hdWDxoq...")
let data = page.data
data.forEach(doc => doc.update({
address: {
state: "District of Columbia"
}
}))
page {
after
}
See Pagination |
---|
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!