The following APIs documented are in a usable state. More APIs are available, however they are not officially supported or complete.
- Public Instance Methods
- initCollection(name, [options], [orbitDbOptions])
- createCollection(name, [options], [orbitDbOptions])
- openCollection(name, [options], [orbitDbOptions])
- dropCollection(name, [options])
- listCollections([filter], [options])
- closeCollection(name)
- collection(name)
- Collection Instance
- insert(docs)
- insertOne(doc)
- find(query)
- findOne(query)
- findOneAndUpdate(filter, modification)
- findOneAndDelete(filter)
- findById(_id)
- findByIdAndDelete(_id)
- findByIdAndUpdate(_id, modification, [options])
- update(filter, modification)
- updateMany(filter, modification)
- deleteOne(filter)
- deleteMany(filter)
- distinct(key, [query])
- getHeadHash()
- syncFromHeadHash(hash, [stopWrites])
- import(data_in, [options], [progressCallback])
- export([options])
- Static Methods
Creates if the collection does not exist, or opens an existing database collection.
Syntax: aviondb.initCollection(name, [options], [orbitDbOptions])
Returns a Promise that resolves to a Collection Instance.
NOTE: It is recommended to use initCollection instead of createCollection and openCollection for better developer experience.
var collection = await aviondb.createCollection("CollectionName");Creates and opens a database collection.
Syntax: aviondb.createCollection(name, [options], [orbitDbOptions])
Returns a Promise that resolves to a Collection Instance. Throws error if a collection with name is already exists.
var collection = await aviondb.createCollection("CollectionName");Opens an existing database collection.
Syntax: aviondb.openCollection(name, [options], [orbitDbOptions])
Returns a Promise that resolves to a Collection Instance. Throws error if a collection with name does not exist.
var collection = await aviondb.openCollection("CollectionName");Deletes collection removing all stored data
Syntax: aviondb.dropCollection(name, [options])
Returns a Promise that resolves on completeion.
Note: this is a network wide operation. Meaning all nodes will remove the collection and all attached data.
await aviondb.dropCollection("Accounts");Lists collections in database.
Syntax: aviondb.listCollections([filter], [options])
Returns a Promise that resolves to an array of collection manifests.
var collectionList = await aviondb.listCollection();
console.log(collectionList);
// [ 'Users', 'Products' ]Closes an open collection.
Syntax: aviondb.closeCollection(name)
This closes the collection. You can open the collection again by openCollection()
await aviondb.closeCollection("Products");Returns collection instance. Throws error if collection is not open.
Syntax: aviondb.collection(name)
Returns a Collection Instance
var collection = aviondb.collection("Accounts");Inserts a list of document into the collection.
Syntax: collection.insert(docs)
Returns a Promise that resolves on completeion.
If _id is not specified in each document a randomly generated id will be assigned.
await collection.insert([
{
name: "jessie",
age: 35,
userId: 971349,
},
]);Inserts a single document into the collection.
Syntax: collection.insertOne(doc)
Returns a Promise that resolves on completeion.
If _id is not specified in document a randomly generated id will be assigned.
await collection.insertOne({
name: "jessie",
age: 35,
userId: 971349,
});Queries the collection returning all results that match query.
Syntax: collection.find(query)
Returns a Promise that resolves to a list of documents
var results = await collection.find({
age: 35,
});
console.log(results);[
{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
},
{
"name": "ali",
"age": 35,
"userId": 85623,
"_id": "5e880642b9b93a4c7dc2d68d"
}
]-
$ltSyntax:
{field: {$lt: value} }$ltselects the documents where the value of thefieldis less than (i.e. <) the specifiedvalue.Consider the following example:
await collection.find({ age: { $lt: 40 } });
This query will select all documents in the
collectionwhere theagefield value is less than40.
-
$lteSyntax:
{field: {$lte: value} }$lteselects the documents where the value of thefieldis less than or equal to (i.e. <=) the specifiedvalue.Consider the following example:
await collection.find({ age: { $lte: 40 } });
This query will select all documents in the
collectionwhere theagefield value is less than or equal to40.
-
$gtSyntax:
{field: {$gt: value} }$gtselects those documents where the value of thefieldis greater than (i.e. >) the specifiedvalue.Consider the following example:
await collection.find({ age: { $gt: 40 } });
This query will select all documents in the
collectionwhere theagefield value is greater than40.
-
$gteSyntax:
{field: {$gte: value} }$gteselects the documents where the value of thefieldis greater than or equal to (i.e. >=) a specifiedvalue(e.g.age.).Consider the following example:
await collection.find({ age: { $gte: 40 } });
This query will select all documents in the
collectionwhere theagefield value is greater than or equal to40.
-
$andSyntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }$andperforms a logical AND operation on an array of one or more expressions (e.g.<expression1>,<expression2>, etc.) and selects the documents that satisfy all the expressions in the array. The$andoperator uses short-circuit evaluation. If the first expression (e.g.<expression1>) evaluates tofalse, AvionDB will not evaluate the remaining expressions.Consider the following example:
await collection.find({ $and: [{ age: { $lt: 30, $gt: 10 } }, { balance: { $gte: 1000 } }], });
This query will select all documents in the
collectionwhere:- the
agefield value is less than30& greater than10and - the
balancefield is greater than or equal to1000.
This query can be also be constructed with an implicit
ANDoperation as follows:await collection.find({ age: { $lt: 30, $gt: 10 }, balance: { $gte: 1000 } });
- the
-
$orSyntax:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }The
$oroperator performs a logicalORoperation on an array of two or more<expressions>and selects the documents that satisfy at least one of the<expressions>.Consider the following example:
await collection.find({ $or: [{ age: { $lt: 30, $gt: 10 } }, { balance: { $gte: 1000 } }], });
This query will select all documents in the
collectionwhere either of the conditions are met:- the
agefield value is less than30and greater than10 - the
balancefield value is greater than or equal to1000
- the
-
limitSyntax:
{ limit: <number> }The
limitspecifies the maximum number of matching records that should be returned from a query.Consider the following example:
await collection.insert([ { name: "kim", age: 35 }, { name: "vasa", age: 22 }, ]); var result = await collection.find({ age: { $gt: 10 } }, null, { limit: 1 }); // result will only have the 1st matching record
This query will only return first
1matching record as specified by thelimitmethod. -
skipSyntax:
{ skip: <number> }The
skipspecifies the number of matching records that should be skipped from a query.Consider the following example:
await collection.insert([ { name: "kim", age: 35 }, { name: "vasa", age: 22 }, ]); var result = await collection.find({ age: { $gt: 10 } }, null, { skip: 1 }); // result will have the 2nd matching record
This query will skip the first matching record (as specified by the
skip) & return all the matching records thereafter. -
sortSyntax:
{ sort: { field: value } }sortspecifies the order in which the query returns matching documents.Specify in the
sortparameter the field or fields to sort by and a value of1or-1to specify an ascending or descending sort respectively.The following sample document specifies a descending sort by the
agefield and then an ascending sort by thepostsfield:{ "age": -1, "posts": 1 }You can also sort by nested field(s) in a document. Following shows an example of sorting documents with respect of a field named
datein an object namedlocals:// posts = [ // { title: 'post 1', locals: { date: '2020-01-09' } }, // { title: 'post 2', locals: { date: '2020-01-02' } }, // { title: 'post 3', locals: { date: '2019-05-06' } }, // ]; var result = await collection.find({}, null, { sort: { "locals.date": 1 })
Consider the following example:
await collection.insert([{ name: "kim", age: 35 },{ name: "vasa", age: 22 }]) var result = await collection.find({}, null, { sort: { age: 1 }) // result will only have the 1st matching record
This query will only return first
1matching record as specified by thelimitmethod.
Queries the collection returning first result matching record.
Syntax: collection.findOne(query)
Returns a Promise that resolves to a single document
var results = await collection.findOne({
age: 35,
});
console.log(results);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Finds first document matching query and modifies it according to specified modification.
Syntax: collection.findOneAndUpdate(filter, modification)
Returns a Promise that resolves to the modified document. Returns an empty document if no document matches the filter
await collection.findOneAndUpdate(
{
age: 35,
},
{
$set: {
age: 40,
},
}
);Finds first document to match query and deletes it from collection.
Syntax: collection.findOneAndDelete(filter)
Returns a Promise that resolves to the original document. Returns an empty document if no document matches the filter
var result = await collection.findOneAndDelete({ age: 35 });
console.log(result);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Queries the collection returning the record with matching BSON ObjectID.
Syntax: collection.findById(_id)
Returns a Promise that resolves to a document with a matching BSON ObjectID.
var ObjectID = require("bson-objectid");
var results = await collection.findById({
_id: ObjectID("5e8cf7e1b9b93a4c7dc2d69e"),
});
console.log(results);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Queries the collection deleting the record with matching BSON ObjectID.
Syntax: collection.findByIdAndDelete(_id)
Returns a Promise that resolves to the original document.
var ObjectID = require("bson-objectid");
var results = await collection.findByIdAndDelete({
_id: ObjectID("5e8cf7e1b9b93a4c7dc2d69e"),
});
console.log(results);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Queries the collection updating the record with matching BSON ObjectID.
Syntax: collection.findByIdAndUpdate(_id, modification, [options])
Returns a Promise resolves to the modified document.
var ObjectID = require("bson-objectid");
var results = await collection.findByIdAndUpdate(
_id: ObjectID("5e8cf7e1b9b93a4c7dc2d69e"),
modification: { $set: { "age": 35 } }
);
console.log(results);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Modifies an existing document or documents in a collection.
Syntax: collection.update(filter, modification, [options])
Returns a Promise that resolves on completion
The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.
By default, the collection.update() method updates a single document.
multi(default:false): Include the optionsmulti: trueto update all documents that match the query criteria.
var results = await collection.update(
{ age: { $lt: 40, $gt: 5 } },
{ $set: { age: 10 } },
{ multi: true }
);
console.log(results);[
{
"name": "jessie",
"age": 10,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
},
{
"name": "vasa",
"age": 10,
"userId": 971350,
"_id": "5e8cf7e1b9b93a4c7dc2d68d"
}
]-
$incThe
$incoperator increments a field by a specified value.Syntax:
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }Behavior
The
$incoperator accepts positive and negative values.If the field does not exist,
$inccreates the field and sets the field to the specified value.Use of the
$incoperator on a field with a null value will generate an error.$incis an atomic operation within a single document.Example
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following
update()operation uses the$incoperator to decrease theagefield by 2 (i.e. increase by -2) and increase thebalancefield by 100:await collection.update( { name: "jessie" }, { $inc: { age: -2, balance: 100 } } );
The updated document would resemble:
{ "name": "jessie", "age": 8, "balance": 1100, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" } -
$minThe
$minupdates the value of the field to a specified value if the specified value is less than the current value of the field.Syntax:
{ $min: { <field1>: <value1>, ... } }Behavior
If the field does not exists, the
$minoperator sets the field to the specified value.Example
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The
balancefor the document currently has the value1000. The following operation uses$minto compare1000to the specified value900and updates the value ofbalanceto900since900is less than1000:await collection.update({ name: "jessie" }, { $min: { balance: 900 } });
The
userscollection now contains the following modified document:{ "name": "jessie", "age": 10, "balance": 900, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The next operation has no effect since the current value of the field
balance, i.e900, is less than2000.await collection.update({ name: "jessie" }, { $min: { balance: 2000 } });
The document remains unchanged in the
userscollection.{ "name": "jessie", "age": 10, "balance": 900, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }
-
$maxThe
$maxoperator updates the value of the field to a specified value if the specified value is greater than the current value of the field.Syntax:
{ $max: { <field1>: <value1>, ... } }Behavior
If the field does not exists, the
$maxoperator sets the field to the specified value.Example
Consider the following document in the collection
users:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The
balancefor the document currently has the value1000. The following operation uses$maxto compare the1000and the specified value2000and updates the value of highScore to2000since2000is greater than1000:await collection.update({ name: "jessie" }, { $max: { balance: 2000 } });
The
userscollection now contains the following modified document:{ "name": "jessie", "age": 10, "balance": 2000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The next operation has no effect since the current value of the field
balance, i.e.2000, is greater than1500:await collection.update({ name: "jessie" }, { $max: { balance: 1500 } });
The document remains unchanged in the
scorescollection:{ "name": "jessie", "age": 10, "balance": 2000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" } -
$mulThe
$mulmultiplies the value of a field by a number.Syntax:
{ $mul: { <field1>: <number1>, ... } }Behavior
If the field does not exist in a document,
$mulcreates the field and sets the value to zero of the same numeric type as the multiplier.Example
Multiply the Value of an existing Field
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following
collection.update()operation updates the document, using the$muloperator to multiply thebalanceby2and theagefield by1.5:await collection.update( { name: "jessie" }, { $mul: { balance: 2, age: 1.25 } } );
The operation results in the following document, where the new value of
balancereflects the original value1000multiplied by2and the new value ofagereflects the original value of10multipled by1.5:{ "name": "jessie", "age": 12.5, "balance": 2000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }Multiply the Value of an non-existing Field
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following
collection.update()operation updates the document, applying the$muloperator to the fieldbalancethat does not exist in the document:await collection.update({ name: "jessie" }, { $mul: { balance: 2 } });
The operation results in the following document with a
balancefield set to value0:{ "name": "jessie", "age": 10, "balance": 0, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" } -
$setThe
$setoperator replaces the value of a field with the specified value.Syntax:
{ $set: { <field1>: <value1>, ... } }Behavior
If the field does not exist,
$setwill add a new field with the specified value, provided that the new field does not violate a type constraint.If you specify multiple field-value pairs,
$setwill update or create each field.Example
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }For the document matching the criteria
_idequal to5e8cf7e1b9b93a4c7dc2d69e, the following operation uses the$setoperator to update the value of theagefield,namefield, and create & set values for a non-existingcompaniesfield.await collection.update( { _id: "5e8cf7e1b9b93a4c7dc2d69e" }, { $set: { age: 48, name: "elon", companies: ["tesla", "spacex", "neuralink"], }, } );
The operation replaces the value of:
ageto48,nametoelon& creates a new fieldcompanieswith value["tesla", "spacex", "neuralink"].{ "name": "elon", "age": 48, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "companies": ["tesla", "spacex", "neuralink"] }
-
$unsetThe
$unsetoperator deletes a particular field.Syntax:
{ $unset: { <field1>: "", ... } }Behavior
If the field does not exist, then
$unsetdoes nothing (i.e. no operation).Example
Consider a collection
userswith the following document:{ "name": "jessie", "age": 10, "balance": 1000, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following
collection.update()operation uses the$unsetoperator to remove the fieldsbalanceandagefrom the first document in theuserscollection where the fieldnamehas a value ofjessie.await collection.update( { name: "jessie" }, { $unset: { balance: "", age: "" } } );
The resulting document will look something like this:
{ "name": "jessie", "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }
-
$renameThe
$renameoperator updates the name of a field.Syntax:
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }Behavior
The
$renameoperator logically performs an$unsetof both the old name and the new name, and then performs a$setoperation with the new name. As such, the operation may not preserve the order of the fields in the document; i.e. the renamed field may move within the document.If the document already has a field with the
<newName>, the$renameoperator removes that field and renames the specified<field>to<newName>.If the field to rename does not exist in a document,
$renamedoes nothing (i.e. no operation).For fields in embedded documents, the
$renameoperator can rename these fields as well as move the fields in and out of embedded documents.$renamedoes not work if these fields are in array elements.Example
A collection
userscontains the following documents where a fieldnmaeappears misspelled, i.e. should bename:[ { "nmae": "jessie", "age": 10, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }, { "nmae": "vasa", "age": 22, "userId": 971350, "_id": "5e8cf7e1b9b93a4c7dc2d68d" } ]To rename a field, call the
$renameoperator with the current name of the field and the new name:await collection.update({}, { $rename: { nmae: "name" } });
This operation renames the field
nmaetonamefor all documents in the collection:[ { "name": "jessie", "age": 10, "userId": 971349, "_id": "5e8cf7e1b9b93a4c7dc2d69e" }, { "name": "vasa", "age": 22, "userId": 971350, "_id": "5e8cf7e1b9b93a4c7dc2d68d" } ] -
$addToSetThe
$addToSetoperator adds a value to an array unless the value is already present, in which case$addToSetdoes nothing to that array.Syntax:
{ $addToSet: { <field1>: <value1>, ... } }Behavior
$addToSetonly ensures that there are no duplicate items added to the set and does not affect existing duplicate elements.$addToSetdoes not guarantee a particular ordering of elements in the modified set.Missing Field
If you use
$addToSeton a field that is absent in the document to update,$addToSetcreates the array field with the specified value as its element.Field is Not an Array
If you use
$addToSeton a field that is not an array, the operation will fail. For example, consider a document in a collection foo that contains a non-array field colors.{ "name": "elon", "userId": 971349, "companies": "tesla,spacex", "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following
$addToSetoperation on the non-array field colors fails:await collection.update( { name: "elon" }, { $addToSet: { companies: "neuralink" } } );
Value to Add is An Array
If the value is an array,
$addToSetappends the whole array as a single element.Consider a document in a collection
userscontaining an array fieldcompanies:{ "name": "elon", "userId": 971349, "companies": ["tesla", "spacex"], "_id": "5e8cf7e1b9b93a4c7dc2d69e" }The following operation appends the array
["neuralink", "openai"]to thecompaniesfield:await collection.update( { name: "elon" }, { $addToSet: { companies: ["neuralink", "openai"] } } );
The
companiesarray now includes the["neuralink", "openai"]array as an element:{ "name": "elon", "userId": 971349, "companies": ["tesla", "spacex", ["neuralink", "openai"]], "_id": "5e8cf7e1b9b93a4c7dc2d69e" }NOTE: To add each element of the value separately, we will support the use of
$eachmodifier with$addToSetin the future releases.Example
Consider a collection
userswith the following document:{ "name": "elon", "userId": 971349, "companies": ["tesla" ,"spacex"], "_id": "5e8cf7e1b9b93a4c7dc2d69e" }Add to Array
The following operation adds the element
"neuralink"to thecompaniesarray since"neuralink"does not exist in the array:await collection.update( { name: "elon" }, { $addToSet: { "companies": "neuralink" } } );
This will result in the following document:
{ "name": "elon", "userId": 971349, "companies": ["tesla" ,"spacex", "neuralink"], "_id": "5e8cf7e1b9b93a4c7dc2d69e" }Value Already Exists
The following
$addToSetoperation has no effect as"spacex"is already an element of thecompaniesarray:await collection.update( { name: "elon" }, { $addToSet: { "companies": "spacex" } } );
-
$popThe
$popoperator removes the first or last element of an array. Pass$popa value of-1to remove the first element of an array and1to remove the last element in an array.Syntax:
{ $pop: { <field>: <-1 | 1>, ... } }Behavior
The
$popoperation fails if the<field>is not an array.If the
$popoperator removes the last item in the<field>, the<field>will then hold an empty array.Example
Remove the First Item of an Array
Given the following document in a collection
users:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "companies": ["tesla", "spacex", "neuralink"] }The following example removes the first element (
"tesla") in thecompaniesarray:await collection.update({ name: "elon" }, { $pop: { companies: -1 } });
After the operation, the updated document has the first item
"tesla"removed from itscompaniesarray:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "companies": ["spacex", "neuralink"] }Remove the Last Item of an Array
Given the following document in a collection
users:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "companies": ["spacex", "neuralink"] }The following example removes the last element (
"neuralink") in thecompaniesarray by specifying1in the$popexpression:await collection.update({ name: "elon" }, { $pop: { companies: 1 } });
After the operation, the updated document has the last item
"neuralink"removed from itscompaniesarray:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "companies": ["spacex"] } -
$pullAllThe
$pullAlloperator removes all instances of the specified values from an existing array. Unlike the$pulloperator that removes elements by specifying a query,$pullAllremoves elements that match the listed values.Syntax:
{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }Behavior
If a
<value>to remove is a document or an array,$pullAllremoves only the elements in the array that match the specified<value>exactly, including order.Example
Given the following document in the
userscollection:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "hours_worked": [12, 13, 13, 14, 15, 10, 12] }The following operation removes all instances of the value
13and12from thehours_workedarray:await collection.update( { name: "elon" }, { $pullAll: { hours_worked: [13, 12] } } );
After the operation, the updated document has all instances of
13and12removed from thehours_workedfield:{ "name": "elon", "age": 48, "_id": "5e8cf7e1b9b93a4c7dc2d69e", "hours_worked": [14, 15, 10] }
Modifies an existing document or documents in a collection.
Syntax: collection.updateOne(filter, modification, [options])
Returns a Promise that resolves on completion
The method can modify specific fields of an existing document or replace an existing document entirely, depending on the update parameter.
var results = await collection.updateOne(
{ age: { $lt: 40, $gt: 30 } },
{ $set: { age: 10 } }
);
console.log(results);{
"name": "jessie",
"age": 10,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Modifies an existing document or documents in a collection.
Syntax: collection.updateMany(filter, modification, [options])
Returns a Promise that resolves on completion
The method can modify specific fields of an existing documents or replace existing documents entirely, depending on the update parameter.
var results = await collection.updateMany(
{ age: { $gt: 10 } },
{ $set: { age: 20 } }
);
console.log(results);[
{
"name": "jessie",
"age": 20,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
},
{
"name": "vasa",
"age": 20,
"userId": 971350,
"_id": "5e8cf7e1b9b93a4c7dc2d68d"
}
]Finds first document to match query and deletes it from collection.
Syntax: collection.deleteOne(filter)
Returns a Promise that resolves to the original document. Returns an empty document if no document matches the filter
var result = await collection.deleteOne({ age: 35 });
console.log(result);{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
}Finds all the documents to match query and deletes them from collection.
Syntax: collection.deleteMany(filter)
Returns a Promise that resolves to the original documents. Returns an empty document if no document matches the filter
var result = await collection.deleteMany({ age: { $gt: 10 } });
console.log(result);[
{
"name": "jessie",
"age": 35,
"userId": 971349,
"_id": "5e8cf7e1b9b93a4c7dc2d69e"
},
{
"name": "vasa",
"age": 22,
"userId": 971350,
"_id": "5e8cf7e1b9b93a4c7dc2d68d"
}
]Retrieves all unique values for the specified key, and query.
Syntax: collection.distinct(key, [query])
Returns a Promise that resolves to an array of values
var results = await collection.distinct("name");
console.log(results); // ["jessie", "ali"]Retrieves CID/multihash representing oplog heads.
Syntax: collection.getHeadHash()
Returns a Promise that resolves to head CID as a base32 encoded string
Rational is to provide a verifiable way that ensures the collection is synced.
var results = await collection.getHeadHash();
console.log(results); //zdpuAtmXUPRPueZocCXRaHwh8Hn6AnByMqupdE3iMboNWa1c1Syncs oplog to head hash.
Syntax: collection.syncFromHeadHash(hash, [stopWrites])
Returns a Promise that resolves on completion
If optional stopWrites is set to true; All write operations will be paused until sync has been completed. Rational is to provide a verifiable way that ensures the collection is synced.
await collection.syncFromHeadHash(
"zdpuAtmXUPRPueZocCXRaHwh8Hn6AnByMqupdE3iMboNWa1c1"
);Import data into AvionDB
Syntax: collection.import(data_in, [options], [progressCallback])
Following parameters are supported by options:
type(string): defines the data format of the data to be imported. Allowed values are:cbor: Documents in cbor Buffer formatjson_mongo: Documents in stringified JSON formatraw: Documents in JSON format
If no type is passed, it defaults to json_mongo.
progressCallback is an optional callback function for checking progress of import process.
It takes 3 parameters currentLength, totalLength, and progressPercent.
currentLength: Length of total data stream imported out oftotalLength.totalLength: Total length of the import data stream.progressPercent: (currentLength/totalLength) *100
Here is an example progressCallback function.
function progressCallback(currentLength, totalLength, progressPercent) {
console.log(currentLength);
console.log(totalLength);
console.log(progressPercent);
}await collection.import(
[
{
name: "jessie",
age: 35,
userId: 971349,
_id: "5e8cf7e1b9b93a4c7dc2d69e",
},
{
name: "vasa",
age: 22,
userId: 971350,
_id: "5e8cf7e1b9b93a4c7dc2d68d",
},
],
{ type: "json_mongo" },
(currentLength, totalLength, progressPercent) => {
console.log(currentLength);
console.log(totalLength);
console.log(progressPercent);
}
);Syncs oplog to head hash.
Syntax: collection.export([options])
Returns a Promise that resolves to Documents to be exported.
Following parameters are supported by options:
-
query(object): Afind()query to filter the documents to be exported. By default, there is no query, hence all the documents are exported. -
type(string): defines the data format of the data to be exported. Allowed values are:cbor: Documents in cbor Buffer formatjson_mongo: Documents in stringified JSON formatraw: Documents resulting fromfind()query, i.e. JSON format.
If no type is passed, it defaults to json_mongo.
cursor(object): Cursor methods likelimit,skip&sortare supported. See Supported Cursor Methods for more details.
await collection.export({
type: "json_mongo",
cursor: {
limit: 100,
skip 10,
sort: { "age": -1 }
},
query: {
age: { $gt: 20 },
},
});Creates a new instance of AvionDB if not present already. If an instance with
nameis exists, then opens and returns the instance.
Syntax: AvionDB.init(name, ipfs, options, orbitDbOptions)
Returns a Promise that resolves to a database instance.
NOTE: It is recommended to use init instead of create & open for better developer experience.
options supports the following parameters:
path: (string): path to be used to store aviondb files. By default it's$HOME/.aviondbfor Linux based systems &C:/Users/Username/.aviondbfor Windows based systems.
orbitDbOptions supports the following options
-
directory(string): path to be used for the database files. By default it uses'./orbitdb'. -
peerId(string): By default it uses the base58 string of the ipfs peer id. -
keystore(Keystore Instance) : By default creates an instance of Keystore. A custom keystore instance can be used, see this for an example. -
cache(Cache Instance) : By default creates an instance of Cache. A custom cache instance can also be used. -
identity(Identity Instance): By default it creates an instance of Identity -
offline(boolean): Start the OrbitDB instance in offline mode. Databases are not be replicated when the instance is started in offline mode. If the OrbitDB instance was started offline mode and you want to start replicating databases, the OrbitDB instance needs to be re-created. Default:false.
Alternatively aviondb can be created from an orbitdb instance. TODO: add docs on proper process.
import AvionDB from "aviondb";
var db = await AvionDB.init("DatabaseName", ipfs, options, orbitDbOptions);Creates a new instance of AvionDB.
Syntax: AvionDB.create(name, ipfs, options, orbitDbOptions)
Returns a Promise that resolves to a database instance. Throws error if a database with name exists already.
orbitDbOptions supports the following options
-
directory(string): path to be used for the database files. By default it uses'./orbitdb'. -
peerId(string): By default it uses the base58 string of the ipfs peer id. -
keystore(Keystore Instance) : By default creates an instance of Keystore. A custom keystore instance can be used, see this for an example. -
cache(Cache Instance) : By default creates an instance of Cache. A custom cache instance can also be used. -
identity(Identity Instance): By default it creates an instance of Identity -
offline(boolean): Start the OrbitDB instance in offline mode. Databases are not be replicated when the instance is started in offline mode. If the OrbitDB instance was started offline mode and you want to start replicating databases, the OrbitDB instance needs to be re-created. Default:false.
Alternatively aviondb can be created from an orbitdb instance. TODO: add docs on proper process.
import AvionDB from "aviondb";
var db = await AvionDB.create("DatabaseName", ipfs, options, orbitDbOptions);Opens an existing instance of AvionDB.
Syntax: AvionDB.open(address, ipfs, options, orbitDbOptions)
Returns a Promise that resolves to a database instance. Throws error if a database with address does not exist already.
orbitDbOptions supports the following options
-
directory(string): path to be used for the database files. By default it uses'./orbitdb'. -
peerId(string): By default it uses the base58 string of the ipfs peer id. -
keystore(Keystore Instance) : By default creates an instance of Keystore. A custom keystore instance can be used, see this for an example. -
cache(Cache Instance) : By default creates an instance of Cache. A custom cache instance can also be used. -
identity(Identity Instance): By default it creates an instance of Identity -
offline(boolean): Start the OrbitDB instance in offline mode. Databases are not be replicated when the instance is started in offline mode. If the OrbitDB instance was started offline mode and you want to start replicating databases, the OrbitDB instance needs to be re-created. Default:false.
Alternatively aviondb can be created from an orbitdb instance. TODO: add docs on proper process.
import AvionDB from "aviondb";
var db = await AvionDB.open(
"/orbitdb/Qmd8TmZrWASypEp4Er9tgWP4kCNQnW4ncSnvjvyHQ3EVSU/DatabaseName",
ipfs,
options,
orbitDbOptions
);Lists the existing databases.
Syntax: AvionDB.listDatabases()
Returns a Promise that resolves to an Array of existing database names.
import AvionDB from "aviondb";
var db = await AvionDB.init("DatabaseName", ipfs, options, orbitDbOptions);
await AvionDB.listDatabases();
// prints ['DatabaseName']Sets configuration for AvionDB.
Syntax: AvionDB.setDatabaseConfig(options)
import AvionDB from "aviondb";
// Sets a custom path for aviondb database list
AvionDB.setDatabaseConfig({ path: "./custom/database/path" });Get configuration for AvionDB.
Syntax: AvionDB.getDatabaseConfig()
import AvionDB from "aviondb";
// Get database configuration
AvionDB.getDatabaseConfig();