Internal
Use Db.collection to obtain an instance of this class.
Private
Readonly
#commandsPrivate
Readonly
#dbPrivate
Readonly
#httpThis temporary error-ing property exists for migration convenience, and will be removed in a future version.
bulkWrite
has been removed until it is supported on the server side by the Data API. Please manually perform equivalent collection operations to attain the same behavior.This temporary error-ing property exists for migration convenience, and will be removed in a future version.
deleteAll
has been removed to retain Data API consistency. Use deleteMany({})
instead to retain the same behavior.Internal
internalReadonly
keyspaceThe keyspace where the collection resides in.
It is up to the user to ensure that this keyspace really exists, and that this collection is in it.
Readonly
nameThe user-provided, case-sensitive. name of the collection
This is unique among all tables and collections in its keyspace, but not necessarily unique across the entire database.
It is up to the user to ensure that this collection really exists.
Backdoor to the HTTP client for if it's absolutely necessary. Which it almost never (if even ever) is.
Counts the number of documents in the collection, optionally with a filter.
See CollectionFilter and CollectionCountDocumentsOptions as well for more information.
A filter to select the documents to count. If not provided, all documents will be counted.
The maximum number of documents to count.
Optional
options: GenericCountOptionsThe options for this operation.
The number of counted documents, if below the provided limit
const count = await collection.countDocuments({ name: 'John Doe' }, 1000);
limit
parameter 🚨🚨Important: This operation takes in a
limit
option which dictates the maximum number of documents that may be present before a TooManyDocumentsToCountError is thrown.If the limit is higher than the highest limit accepted by the Data API (i.e.
1000
), a TooManyDocumentsToCountError will be thrown anyway.
await collection.insertMany([
{ name: 'John Doe' },
{ name: 'Jane Doe' },
]);
const count = await collection.countDocuments({}, 1000);
console.log(count); // 1
// Will throw a TooManyDocumentsToCountError as it counts 2, but the limit is 1
const count = await collection.countDocuments({}, 1);
Count operations are expensive: for this reason, the best practice is to provide a reasonable upperBound
according to the caller expectations. Moreover, indiscriminate usage of count operations for sizeable amounts
of documents (i.e. in the thousands and more) is discouraged in favor of alternative application-specific
solutions. Keep in mind that the Data API has a hard upper limit on the amount of documents it will count,
and that an exception will be thrown by this method if this limit is encountered.
TooManyDocumentsToCountError - If the number of documents counted exceeds the provided limit.
Deletes many documents from the collection.
See CollectionFilter, CollectionDeleteManyOptions, and CollectionDeleteManyResult as well for more information.
A filter to select the documents to delete.
Optional
options: GenericDeleteManyOptionsThe options for this operation.
How many documents were deleted.
await collection.insertMany([
{ name: 'John Doe', age: 1 },
{ name: 'John Doe', age: 2 },
]);
await collection.deleteMany({ name: 'John Doe' });
🚨Important: This function paginates the deletion of documents due to server deletion limits, which means it may make multiple requests to the server. As a result, this operation is not necessarily atomic.
Depending on the amount of matching documents, it can keep running (in a blocking manner) for a macroscopic amount of time. During this time, documents that are modified/inserted from another concurrent process/application may be modified/inserted during the execution of this method call.
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
🚨Important: If an empty filter is passed, all documents in the collection will atomically be deleted in a single API call. Proceed with caution.
await collection.insertMany([
{ name: 'John Doe' },
{ name: 'Jane Doe' },
]);
const resp = await collection.deleteMany({});
console.log(resp.deletedCount); // -1
Atomically deletes a single document from the collection.
See CollectionFilter, CollectionDeleteOneOptions, and CollectionDeleteOneResult as well for more information.
A filter to select the document to delete.
Optional
options: GenericDeleteOneOptionsThe options for this operation.
How many documents were deleted.
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.deleteOne({ name: 'John Doe' });
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can delete the most relevant document by providing a vector in the sort option.
await collection.insertOne({ name: 'John Doe', $vector: [.12, .52, .32] });
await collection.deleteOne({}, { sort: { $vector: [.11, .53, .31] }});
Return a list of the unique values of key
across the documents in the collection that match the provided filter.
See CollectionFilter and CollectionDistinctOptions as well for more information.
The dot-notation key to pick which values to retrieve unique
A filter to select the documents to find. If not provided, all documents will be matched.
Optional
options: GenericDistinctOptionsThe options for this operation.
A list of all the unique values selected by the given key
const docs = await collection.distinct('name');
🚨Important: This is a client-side operation.
This method browses all matching documents (albeit with a projection) using the logic of the Collection.find method, and collects the unique value for the given
key
manually.As such, there may be performance, latency, and ultimately billing implications if the amount of matching documents is large.
Therefore, it is heavily recommended to only use this method on small datasets, or a strict filter.
The key may use dot-notation to access nested fields, such as 'field'
, 'field.subfield'
, 'field.3'
, 'field.3.subfield'
, etc. If lists are encountered and no numeric index is specified, all items in the list are pulled.
✏️Note: On complex extractions, the return type may be not as expected.** In that case, it's on the user to cast the return type to the correct one.
Distinct works with arbitrary objects as well, by stable-y stringifying the object and comparing it with the string representations of the objects already seen.
For details on the behavior of "distinct" in conjunction with real-time changes in the collection contents, see the remarks on the find
command.
await collection.insertMany([
{ letter: { value: 'a' }, car: [1] },
{ letter: { value: 'b' }, car: [2, 3] },
{ letter: { value: 'a' }, car: [2], bus: 'no' },
]);
// ['a', 'b']
const distinct = await collection.distinct('letter.value');
await collection.insertOne({
x: [{ y: 'Y', 0: 'ZERO' }],
});
// ['Y']
await collection.distinct('x.y');
// [{ y: 'Y', 0: 'ZERO' }]
await collection.distinct('x.0');
// ['Y']
await collection.distinct('x.0.y');
// ['ZERO']
await collection.distinct('x.0.0');
Optional
options: Omit<DropCollectionOptions, keyof WithKeyspace>The options for this operation.
A promise which resolves when the collection has been dropped.
const collection = await db.collection('my_collection');
await collection.drop();
🚨Important: Once the collection is dropped, this object is still technically "usable", but any further operations on it will fail at the Data API level; thus, it's the user's responsibility to make sure that the Collection object is no longer used.
Use with caution. Wear your safety goggles. Don't say I didn't warn you.
Gets an estimate of the count of documents in a collection.
This gives a very rough estimate of the number of documents in the collection. It is not guaranteed to be accurate, and should not be used as a source of truth for the number of documents in the collection.
However, this operation is faster than Collection.countDocuments, and while it doesn't accept a filter, it can handle any number of documents.
See CollectionEstimatedDocumentCountOptions as well for more information.
Optional
options: GenericEstimatedCountOptionsThe options for this operation.
The estimated number of documents in the collection
const count = await collection.estimatedDocumentCount();
console.log(count); // Hard to predict exact number
CollectionEstimatedDocumentCountOptions
Find documents in the collection, optionally matching the provided filter.
See CollectionFilter, CollectionFindOptions, and FindCursor as well for more information.
A filter to select the documents to find. If not provided, all documents will be returned.
Optional
options: GenericFindOptionsThe options for this operation.
a FindCursor which can be iterated over.
const cursor = await collection.find({ name: 'John Doe' }, { sort: { age: 1 } });
const docs = await cursor.toArray();
const cursor = await collection.find({})
.sort({ age: 1 })
.project<{ name: string }>({ name: 1 })
.map(doc => doc.name);
// ['John Doe', 'Jane Doe', ...]
const names = await cursor.toArray();
🚨Important: When projecting, it is heavily recommended to provide an explicit type override representing the projected schema, to prevent any type-mismatches when the schema is strictly provided.
Otherwise, the documents will be typed as the full
Schema
, which may lead to runtime errors when trying to access properties that are not present in the projected documents.
💡Tip: Use the Pick or Omit utility types to create a type representing the projected schema.
interface User {
name: string,
car: { make: string, model: string },
}
const collection = db.collection<User>('users');
// --- Not providing a type override ---
const cursor = await collection.find({}, {
projection: { car: 1 },
});
const next = await cursor.next();
console.log(next.car.make); // OK
console.log(next.name); // Uh oh! Runtime error, since tsc doesn't complain
// --- Explicitly providing the projection type ---
const cursor = await collection.find<Pick<User, 'car'>>({}, {
projection: { car: 1 },
});
const next = await cursor.next();
console.log(next.car.make); // OK
console.log(next.name); // Type error; won't compile
The filter can contain a variety of operators & combinators to select the documents. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, all documents in the collection will be returned (up to any provided or server limit).
If the collection has vector search enabled, you can find the most relevant documents by providing a vector in the sort option.
Vector ANN searches cannot return more than a set number of documents, which, at the time of writing, is 1000 items.
await collection.insertMany([
{ name: 'John Doe', $vector: [.12, .52, .32] },
{ name: 'Jane Doe', $vector: [.32, .52, .12] },
{ name: 'Dane Joe', $vector: [.52, .32, .12] },
]);
const cursor = collection.find({}, {
sort: { $vector: [.12, .52, .32] },
});
// Returns 'John Doe'
console.log(await cursor.next());
The sort option can be used to sort the documents returned by the cursor. See Sort for more information.
If the sort option is not provided, there is no guarantee as to the order of the documents returned.
🚨Important: When providing a non-vector sort, the Data API will return a smaller number of documents (20, at the time of writing), and stop there. The returned documents are the top results across the whole collection according to the requested criterion.
await collection.insertMany([
{ name: 'John Doe', age: 1, height: 168 },
{ name: 'John Doe', age: 2, height: 42 },
]);
const cursor = collection.find({}, {
sort: { age: 1, height: -1 },
});
// Returns 'John Doe' (age 2, height 42), 'John Doe' (age 1, height 168)
console.log(await cursor.toArray());
Other available options include skip
, limit
, includeSimilarity
, and includeSortVector
. See CollectionFindOptions and FindCursor for more information.
If you prefer, you may also set these options using a fluent interface on the FindCursor itself.
// cursor :: FindCursor<string>
const cursor = collection.find({})
.sort({ $vector: [.12, .52, .32] })
.projection<{ name: string, age: number }>({ name: 1, age: 1 })
.includeSimilarity(true)
.map(doc => `${doc.name} (${doc.age})`);
When not specifying sorting criteria at all (by vector or otherwise), the cursor can scroll through an arbitrary number of documents as the Data API and the client periodically exchange new chunks of documents.
--
It should be noted that the behavior of the cursor in the case documents
have been added/removed after the find
was started depends on database
internals, and it is not guaranteed, nor excluded, that such "real-time"
changes in the data would be picked up by the cursor.
Beta
Finds documents in a collection through a retrieval process that uses a reranker model to combine results from a vector similarity search and a lexical-based search (aka a "hybrid search").
Disclaimer: this method is currently in preview/beta in this release of the client.
Optional
options: GenericFindAndRerankOptions// With vectorize
const cursor = await coll.findAndRerank({})
.sort({ $hybrid: 'what is a dog?' })
.includeScores();
// Using your own vectors
const cursor = await coll.findAndRerank({})
.sort({ $hybrid: { $vector: vector([...]), $lexical: 'what is a dog?' } })
.rerankOn('$lexical')
.rerankQuery('I like dogs');
for await (const res of cursor) {
console.log(cursor.document, cursor.scores);
}
Find a single document in the collection, optionally matching the provided filter.
See CollectionFilter and CollectionFindOneOptions as well for more information.
A filter to select the documents to find. If not provided, all documents will be returned.
Optional
options: GenericFindOneOptionsThe options for this operation.
A document matching the criterion, or null
if no such document exists.
const doc = await collection.findOne({ name: 'John Doe' });
🚨Important: When projecting, it is heavily recommended to provide an explicit type override representing the projected schema, to prevent any type-mismatches when the schema is strictly provided.
Otherwise, the document will be typed as the full
Schema
, which may lead to runtime errors when trying to access properties that are not present in the projected document.
💡Tip: Use the Pick or Omit utility types to create a type representing the projected schema.
interface User {
name: string,
car: { make: string, model: string },
}
const collection = db.collection<User>('users');
// --- Not providing a type override ---
const doc = await collection.findOne({}, {
projection: { car: 1 },
});
console.log(doc.car.make); // OK
console.log(doc.name); // Uh oh! Runtime error, since tsc doesn't complain
// --- Explicitly providing the projection type ---
const doc = await collection.findOne<Pick<User, 'car'>>({}, {
projection: { car: 1 },
});
console.log(doc.car.make); // OK
console.log(doc.name); // Type error; won't compile
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can find the most relevant document by providing a vector in the sort option.
await collection.insertMany([
{ name: 'John Doe', $vector: [.12, .52, .32] },
{ name: 'Jane Doe', $vector: [.32, .52, .12] },
{ name: 'Dane Joe', $vector: [.52, .32, .12] },
]);
const doc = collection.findOne({}, {
sort: { $vector: [.12, .52, .32] },
});
// 'John Doe'
console.log(doc.name);
The sort option can be used to pick the most relevant document. See Sort for more information.
If the sort option is not provided, there is no guarantee as to which of the documents which matches the filter is returned.
await collection.insertMany([
{ name: 'John Doe', age: 1, height: 168 },
{ name: 'John Doe', age: 2, height: 42 },
]);
const doc = collection.findOne({}, {
sort: { age: 1, height: -1 },
});
// 'John Doe' (age 2, height 42)
console.log(doc.name);
Other available options include includeSimilarity
. See CollectionFindOneOptions for more information.
If you want to get skip
or includeSortVector
as well, use Collection.find with a limit: 1
instead.
const doc = await cursor.findOne({}, {
sort: { $vector: [.12, .52, .32] },
includeSimilarity: true,
});
Atomically finds a single document in the collection and deletes it.
See CollectionFilter and CollectionFindOneAndDeleteOptions as well for more information.
A filter to select the document to find.
Optional
options: GenericFindOneAndDeleteOptionsThe options for this operation.
The deleted document, or null
if no document was found.
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.findOneAndDelete({ _id: '1' });
🚨Important: When projecting, it is heavily recommended to provide an explicit type override representing the projected schema, to prevent any type-mismatches when the schema is strictly provided.
Otherwise, the returned document will be typed as the full
Schema
, which may lead to runtime errors when trying to access properties that are not present in the projected document.
💡Tip: Use the Pick or Omit utility types to create a type representing the projected schema.
await collection.insertOne({ _id: '1', name: 'John Doe', age: 3 });
const doc = await collection.findOneAndDelete<{ name: string }>(
{ _id: '1' },
{ projection: { name: 1, _id: 0 } },
);
// Prints { name: 'John Doe' }
console.log(doc);
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can delete the most relevant document by providing a vector in the sort option.
See Collection.deleteOne for a concrete example.
Atomically finds a single document in the collection and replaces it.
See CollectionFilter and CollectionFindOneAndReplaceOptions as well for more information.
A filter to select the document to find.
The replacement document, which contains no _id
field.
Optional
options: GenericFindOneAndReplaceOptionsThe options for this operation.
The document before/after replacement, depending on the type of returnDocument
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.findOneAndReplace({ _id: '1' }, { name: 'Dohn Joe' });
🚨Important: When projecting, it is heavily recommended to provide an explicit type override representing the projected schema, to prevent any type-mismatches when the schema is strictly provided.
Otherwise, the returned document will be typed as the full
Schema
, which may lead to runtime errors when trying to access properties that are not present in the projected document.
💡Tip: Use the Pick or Omit utility types to create a type representing the projected schema.
await collection.insertOne({ _id: '1', name: 'John Doe', age: 3 });
const doc = await collection.findOneAndReplace<{ name: string }>(
{ _id: '1' },
{ name: 'Dohn Joe' },
{ projection: { name: 1, _id: 0 } },
);
// Prints { name: 'John Doe' }
console.log(doc);
If upsert
is set to true, it will insert the document reconstructed from the filter & the update filter if no match is found.
const resp = await collection.findOneAndReplace(
{ _id: 42 },
{ name: 'Jessica' },
{ upsert: true },
);
console.log(resp); // null, b/c no previous document was found
returnDocument
returnDocument
(default 'before'
) controls whether the original or the updated document is returned.
'before'
: Returns the document as it was before the update, or null
if the document was upserted.'after'
: Returns the document as it is after the update.await collection.insertOne({ _id: '1', name: 'John Doe' });
const after = await collection.findOneAndReplace(
{ _id: '1' },
{ name: 'Jane Doe' },
{ returnDocument: 'after' },
);
// Prints { _id: '1', name: 'Jane Doe' }
console.log(after);
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can replace the most relevant document by providing a vector in the sort option.
See Collection.replaceOne for a concrete example.
Atomically finds a single document in the collection and updates it.
See CollectionFilter and CollectionFindOneAndUpdateOptions as well for more information.
A filter to select the document to find.
The update to apply to the selected document.
Optional
options: GenericFindOneAndUpdateOptionsThe options for this operation.
The document before/after the update, depending on the type of returnDocument
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.findOneAndUpdate({ _id: '1' }, { $set: { name: 'Jane Doe' } });
🚨Important: When projecting, it is heavily recommended to provide an explicit type override representing the projected schema, to prevent any type-mismatches when the schema is strictly provided.
Otherwise, the returned document will be typed as the full
Schema
, which may lead to runtime errors when trying to access properties that are not present in the projected document.
💡Tip: Use the Pick or Omit utility types to create a type representing the projected schema.
await collection.insertOne({ _id: '1', name: 'John Doe', age: 3 });
const doc = await collection.findOneAndUpdate<{ name: string }>(
{ _id: '1' },
{ $set: { name: 'Jane Doe' } },
{ projection: { name: 1, _id: 0 } },
);
// Prints { name: 'John Doe' }
console.log(doc);
If upsert
is set to true, it will insert the document reconstructed from the filter & the update filter if no match is found.
const resp = await collection.findOneAndUpdate(
{ _id: 42 },
{ $set: { name: 'Jessica' } },
{ upsert: true },
);
console.log(resp); // null, b/c no previous document was found
returnDocument
returnDocument
(default 'before'
) controls whether the original or the updated document is returned.
'before'
: Returns the document as it was before the update, or null
if the document was upserted.'after'
: Returns the document as it is after the update.await collection.insertOne({ _id: '1', name: 'John Doe' });
const after = await collection.findOneAndUpdate(
{ _id: '1' },
{ $set: { name: 'Jane Doe' } },
{ returnDocument: 'after' },
);
// Prints { _id: '1', name: 'Jane Doe' }
console.log(after);
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can update the most relevant document by providing a vector in the sort option.
See Collection.updateOne for a concrete example.
Inserts many documents into the collection.
See CollectionInsertManyOptions and CollectionInsertManyResult as well for more information.
The documents to insert.
Optional
options: GenericInsertManyOptionsThe options for this operation.
The IDs of the inserted documents (and the count)
import { uuid } from '@datastax/astra-db-ts';
await collection.insertMany([
{ _id: uuid.v4(), name: 'John Doe' }, // or UUID.v4()
{ name: 'Jane Doe' },
]);
🚨Important: This function inserts documents in chunks to avoid exceeding insertion limits, which means it may make multiple requests to the server. As a result, this operation is not necessarily atomic.
If the dataset is large or the operation is ordered, it may take a relatively significant amount of time. During this time, documents inserted by other concurrent processes may be written to the database, potentially causing duplicate id conflicts. In such cases, it's not guaranteed which write will succeed.
By default, it inserts documents in chunks of 50 at a time. You can fine-tune the parameter through the chunkSize
option. Note that increasing chunk size won't always increase performance. Instead, increasing concurrency may help.
You can set the concurrency
option to control how many network requests are made in parallel on unordered insertions. Defaults to 8
.
const docs = Array.from({ length: 100 }, (_, i) => ({ _id: i }));
await collection.insertMany(docs, { concurrency: 16 });
You may set the ordered
option to true
to stop the operation after the first error; otherwise documents may be parallelized and processed in arbitrary order, improving, perhaps vastly, performance.
Setting the ordered
operation disables any parallelization so insertions truly are stopped after the very first error.
// Will throw an InsertManyError after the 2nd doc is inserted with a duplicate key;
// the 3rd doc will never attempt to be inserted
await collection.insertMany([
{ _id: '1', name: 'John Doe' },
{ _id: '1', name: 'John Doe' },
{ _id: '2', name: 'Jane Doe' },
], {
ordered: true,
});
_id
fieldIf the document does not contain an _id
field, the server will generate an _id for the document.
If an _id
is provided which corresponds to a document that already exists in the collection, a DataAPIResponseError is raised, and the insertion fails.
💡Tip: See SomeId for much more information on the
_id
field.
// Insert documents with autogenerated IDs
await collection.insertMany([
{ name: 'John Doe' },
{ name: 'Jane Doe' },
]);
// Use the inserted IDs (generated or not)
const resp = await collection.insertMany([
{ name: 'Lemmy' },
{ name: 'Kilmister' },
]);
console.log(resp.insertedIds); // will be string UUIDs
// Or if the collection has a default ID
const collection = db.createCollection('users', {
defaultId: { type: 'objectId' },
});
const resp = await collection.insertMany([
{ name: 'Lynyrd' },
{ name: 'Skynyrd' },
]);
console.log(resp.insertedIds[0].getTimestamp()); // will be ObjectIds
CollectionInsertManyError
If any 2XX insertion error occurs, the operation will throw an CollectionInsertManyError containing the partial result.
If a thrown exception is not due to an insertion error, e.g. a 5xx
error or network error, the operation will throw the underlying error.
In case of an unordered request, if the error was a simple insertion error, the CollectionInsertManyError will be thrown after every document has been attempted to be inserted. If it was a 5xx
or similar, the error will be thrown immediately.
CollectionInsertManyError - If the operation fails.
Atomically inserts a single document into the collection.
See CollectionInsertOneOptions and CollectionInsertOneResult as well for more information.
The document to insert.
Optional
options: GenericInsertOneOptionsThe options for this operation.
The ID of the inserted document.
import { UUID, ObjectId, ... } from '@datastax/astra-db-ts';
// Insert a document with a specific ID
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.insertOne({ _id: new ObjectID(), name: 'Jane Doe' });
await collection.insertOne({ _id: UUID.v7(), name: 'Dane Joe' });
// Insert a document with a vector (if enabled on the collection)
await collection.insertOne({ _id: 1, name: 'Jane Doe', $vector: [.12, .52, .32] });
// or if vectorize (auto-embedding-generation) is enabled
await collection.insertOne({ _id: 1, name: 'Jane Doe', $vectorize: "Hey there!" });
_id
fieldIf the document does not contain an _id
field, the server will generate an _id for the document.
If an _id
is provided which corresponds to a document that already exists in the collection, a DataAPIResponseError is raised, and the insertion fails.
If you prefer to upsert a document instead, see Collection.replaceOne.
💡Tip: See SomeId for much more information on the
_id
field.
// Insert a document with an autogenerated ID
await collection.insertOne({ name: 'Jane Doe' });
// Use the inserted ID (generated or not)
const resp = await collection.insertOne({ name: 'Lemmy' });
console.log(resp.insertedId);
// Or if the collection has a default ID
const collection = db.createCollection('users', {
defaultId: { type: 'uuid' },
});
const resp = await collection.insertOne({ name: 'Lemmy' });
console.log(resp.insertedId.version); // 4
Unsubscribe from an event.
The event to unsubscribe from.
The listener to remove.
Subscribe to an event.
The event to listen for.
The callback to invoke when the event is emitted.
A function to unsubscribe the listener.
Subscribe to an event once.
The listener will be automatically unsubscribed after the first time it is called.
Note that the listener will be unsubscribed BEFORE the actual listener callback is invoked.
The event to listen for.
The callback to invoke when the event is emitted.
A function to prematurely unsubscribe the listener.
Get the collection options, i.e. its configuration as read from the database.
The method issues a request to the Data API each time it is invoked, without caching mechanisms; this ensures up-to-date information for usages such as real-time collection validation by the application.
Optional
options: WithTimeout<"collectionAdminTimeoutMs">The options for this operation.
The options that the collection was created with (i.e. the vector
and indexing
operations).
const options = await collection.info();
console.log(options.vector);
Remove all listeners for an event.
If no event is provided, all listeners for all events will be removed.
Optional
eventName: EThe event to remove listeners for.
Replaces a single document in the collection.
See CollectionFilter, CollectionReplaceOneOptions, and CollectionReplaceOneResult as well for more information.
A filter to select the document to replace.
The replacement document, which contains no _id
field.
Optional
options: GenericReplaceOneOptionsThe options for this operation.
A summary of what changed.
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.replaceOne({ _id: '1' }, { name: 'Dohn Joe' });
If upsert
is set to true, it will insert the document reconstructed from the filter & the update filter if no match is found.
const resp = await collection.replaceOne(
{ _id: 42 },
{ name: 'Jessica' },
{ upsert: true },
);
if (resp.upsertedCount) {
console.log(resp.upsertedId); // 42
}
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can replace the most relevant document by providing a vector in the sort option.
await collection.insertOne({ name: 'John Doe', $vector: [.12, .52, .32] });
await collection.replaceOne(
{ optionalFilter },
{ name: 'Jane Doe', $vectorize: 'Come out and play' },
{ sort: { $vector: [.11, .53, .31] } },
);
Updates many documents in the collection.
See CollectionFilter, CollectionUpdateFilter, CollectionUpdateManyOptions, and CollectionUpdateManyResult as well for more information.
A filter to select the documents to update.
The update to apply to the selected documents.
Optional
options: GenericUpdateManyOptionsThe options for this operation.
A summary of what changed.
await collection.insertMany([
{ name: 'John Doe', age: 30 },
{ name: 'Jane Doe', age: 30 },
]);
await collection.updateMany({ age: 30 }, { $set: { age: 31 } });
🚨Important: This function paginates the updating of documents due to server update limits, which means it may make multiple requests to the server. As a result, this operation is not necessarily atomic.
Depending on the amount of matching documents, it can keep running (in a blocking manner) for a macroscopic amount of time. During this time, documents that are modified/inserted from another concurrent process/application may be modified/inserted during the execution of this method call.
If upsert
is set to true, it will insert the document reconstructed from the filter & the update filter if no match is found.
Only one document may be upserted per command.
const resp = await collection.updateMany(
{ name: 'Kasabian' },
{ $set: { age: 27 }, $setOnInsert: { _id: 42 } },
{ upsert: true },
);
if (resp.upsertedCount) {
console.log(resp.upsertedId); // 42
}
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
🚨Important: If the filter is empty, all documents in the collection will (non-atomically) be updated. Proceed with caution.
Atomically updates a single document in the collection.
See CollectionFilter, CollectionUpdateFilter, CollectionUpdateOneOptions, and CollectionUpdateOneResult as well for more information.
A filter to select the document to update.
The update to apply to the selected document.
Optional
options: GenericUpdateOneOptionsThe options for this operation.
A summary of what changed.
await collection.insertOne({ _id: '1', name: 'John Doe' });
await collection.updateOne({ _id: '1' }, { $set: { name: 'Jane Doe' } });
If upsert
is set to true, it will insert the document reconstructed from the filter & the update filter if no match is found.
const resp = await collection.updateOne(
{ _id: 42 },
{ $set: { age: 27 }, $setOnInsert: { name: 'Kasabian' } },
{ upsert: true },
);
if (resp.upsertedCount) {
console.log(resp.upsertedId); // 42
}
The filter can contain a variety of operators & combinators to select the document. See CollectionFilter for much more information.
⚠️Warning: If the filter is empty, and no Sort is present, it's undefined as to which document is selected.
If the collection has vector search enabled, you can update the most relevant document by providing a vector in the sort option.
await collection.updateOne(
{ optionalFilter },
{ $set: { name: 'Jane Doe', $vectorize: 'Come out and play' } },
{ sort: { $vector: [.09, .58, .21] } },
);
Overview
Represents the interface to a collection in a Data-API-enabled database.
Example
Typing the collection
Collections are inherently untyped, but you can provide your own client-side compile-time schema for type inference and early-bug-catching purposes.
A
Collection
is typed asCollection<WSchema, RSchema>
, where:WSchema
is the type of the row as it's written to the table (the "write" schema)RSchema
is the type of the row as it's read from the table (the "read" schema)WSchema
FoundDoc<WSchema>
(see FoundDoc)Typing the
_id
The
_id
field of the document may be any valid JSON scalar (including Date, UUID, and ObjectId)._id
s.The type of the
_id
field is extracted from the collection schema via the IdOf utility type.Example
Datatypes
Certain datatypes may be represented as TypeScript classes (some native, some provided by
astra-db-ts
), however.For example:
$date
is represented by a native JS Date$uuid
is represented by anastra-db-ts
provided UUID$vector
is represented by anastra-db-ts
provided DataAPIVectorYou may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Example
The full list of relevant datatypes (for collections) includes: UUID, ObjectId, Date, DataAPIVector and BigNumber.
Big numbers
By default, big numbers (
bigint
s and BigNumbers frombignumber.js
) are disabled, and will error when attempted to be serialized, and will lose precision when deserialized.See CollectionSerDesConfig.enableBigNumbers for more information on enabling big numbers in collections.
Custom datatypes
You can plug in your own custom datatypes, as well as enable many other features by providing some custom serialization/deserialization logic through the
serdes
option in CollectionOptions, DbOptions, and/or DataAPIClientOptions.dbOptions.Note however that this is currently not entirely stable, and should be used with caution.
🚨Disclaimers
Collections are inherently untyped. There is no runtime type validation or enforcement of the schema.
It is on the user to ensure that the TS type of the
Collection
corresponds with the actual intended collection schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviors and easily-preventable errors.See