Insert Documents
To insert new document just use insert model's method
const user: User = await userModel.insert({
name: 'John',
position: {
x: 1,
y: 1
},
createdAt: new Date().toISOString()
});
This method will return the Promise with inserted document (property _id will be added automatically, you don't need to specify it in schema). Returned document is a simple object that doesn't have any specific methods:
{
_id: 'dc4628514b81-939f-198a25f76b7-bb1a9a777',
name: 'John',
position: {
x: 1,
y: 1
},
isActive: true
createdAt: '2025-06-18T06:30:24.977Z'
}
Insert many documents
insertMany sends the documents in batches: one request and one disk write per batch instead of one per document. Inserting 10,000 small documents over one connection took 5.9 s with insert and 0.15 s with insertMany. It needs Server and ODM 4.6.5 or newer.
const users: User[] = await userModel.insertMany([
{ name: 'John', createdAt: new Date().toISOString() },
{ name: 'Jane', createdAt: new Date().toISOString() }
]);
// optional: a transaction and the batch size
await userModel.insertMany(documents, transactionId, 5000);
| Argument | Description |
|---|---|
| documents | Array of documents. Defaults and setters apply to each one, as in insert |
| transactionId | Optional. The documents become visible when the transaction is committed |
| batchSize | Optional. Documents per request: 1 to 10000, default 1000 |
The inserted documents are returned in the order they were given, each with its _id.
A batch is stored completely or not at all: when one document is invalid (also a
unique value repeated inside the batch), the error names its position and nothing of that batch is stored. Batches sent before it stay inserted. Use a transaction when all documents must be stored together.