Skip to main content

Insert or Replace Documents

To insert one or more documents in Tigris, you can use Insert or Replace API.

Example collection

The first step is to set up the collection object. All the operations on the collection are performed through this collection object.

const catalog = db.getCollection<Catalog>("catalog");

Insert a Single Document

Insert API can be used to insert one or more documents into the collection. Since the id field is marked as autoGenerate, you don't need to specify a value for it and Tigris will automatically generate it for you.

const insertedProduct = await catalog.insertOne({
name: "fiona handbag",
price: 99.9,
brand: "michael kors",
labels: "purses",
popularity: 8,
});

The insert API maintains the uniqueness of the field marked as the primary key, for example, the field id in the example above. If the document with the same primary key value already exists in the collection, the operation will fail by throwing an HTTP status code 409 with the message "duplicate key value, violates key constraint"

Insert Multiple Documents

Similar, to a single row insert, you can also insert multiple documents by passing an array of documents.

const products: Array<Catalog> = [
{
name: "tote bag",
price: 49,
brand: "coach",
labels: "handbags",
popularity: 9,
},
{
name: "sling bag",
price: 75,
brand: "coach",
labels: "purses",
popularity: 9,
}
];

const insertedProducts = await catalog.insertMany(products);

Replace a Single Document

Insert or replace operation can be used to insert a new document or replace an existing document with the same primary key value. This API is useful when there is no need for a uniqueness check on the primary key, and it is fine to replace documents that already exist. The following is an example when the row with an id 3 already exists so the below operation will replace the document with the newly provided data.

const product = await catalog.insertOrReplaceOne({
id: 3,
name: "sling bag",
price: 75,
brand: "coach",
labels: "purses",
popularity: 9,
});

Replace Multiple Documents

As the API can also be used when the document doesn't exist. The following is an example of when these two documents are inserted because there are no corresponding ids.

const products: Array<Catalog> = [
{
name: "sneakers shoes",
price: 40,
brand: "adidas",
labels: "shoes",
popularity: 10,
},
{
name: "running shoes",
price: 89,
brand: "coach",
labels: "shoes",
popularity: 10,
};
];

const insertedOrReplacedProducts = await catalog.insertOrReplaceMany(products);