Skip to main content

Find Document

The findOne and findMany methods are used to retrieve documents from a collection in a Zero-Knowledge Database (zkDatabase). These methods allow querying the database based on specified criteria, supporting both single document fetches and bulk retrievals.

Definition​

The findOne function retrieves a single document that matches the given filter criteria, while the findMany function fetches all documents that match the filter.

const doc = (await collection.findOne(filter)).unwrap();
const docs = (await collection.findMany(filter, pagination)).unwrap();

Parameters​

  • filter: Record<string, any> - An object representing the criteria to be used for filtering documents within the collection. Each key-value pair corresponds to a document field and the desired value for that field (e.g., { name: 'Test Shirt' }).
  • pagination: TPagination - An optional object that specifies pagination parameters for the query (e.g: { limit: 5, offset: 0 }).

Returns​

  • findOne: Returns a Result containing a single document object if found, or null if no document matches.
  • findMany: Returns a Result containing a TPaginationReturn<Document[]> object with matching documents.
type TPaginationReturn<T> = {
data: T;
total: number;
offset: number;
};

Example​

Here is an example demonstrating how to use findOne and findMany to retrieve documents from a collection:

import { ZkDatabase } from 'zkdb';

const zkdb = new ZkDatabase({
apiKey: 'zkdb_536aac02a1b7.c001b6b8f...da3aa4185d8d2ad07f0ae94aT',
// This URL is for test environment
url: "https://serverless.zkdatabase.org/graphql",
});
class Shirt extends Schema.create({
name: String,
price: UInt64,
}) {}

type TShirt = typeof Shirt;

const collection = await zkdb
.db('zkdb_test')
.collection<TShirt>('test_collection');

const doc = await collection.findOne({ name: 'Test Shirt' });

if (doc) {
console.log(doc.document);
}

const listDoc = await collection.findMany(undefined, { limit: 10, offset: 0 });

listDoc.data.forEach((item) => {
console.log(item.document);
});