Import & Export
You can load documents from an external JSON file into a collection,
and you can export a collection by simply reading its part files
or by using a backup with the pack option.
Import
collection.import(filePath, options?) reads a JSON file and
inserts its documents into the collection.
Accepted file shapes
- A top-level JSON array of documents
- An object with a
dataordocumentsarray property
// users.json
[
{ "name": "Alice", "email": "alice@example.com" },
{ "name": "Bob", "email": "bob@example.com" }
]
// or
{
"documents": [
{ "name": "Alice", "email": "alice@example.com" }
]
}
Usage
// Append the file contents to the collection
const ok = users.import('./seed/users.json');
console.log(ok); // true on success, false on error
// Clear the collection first, then import
users.import('./seed/users.json', { clear: true });
// Async version (goes through the lock)
await users.importAsync('./seed/users.json', { clear: true });
On success the collection emits an import event with
{ collection, count }.
Options
| Option | Type | Default | Meaning |
|---|---|---|---|
clear |
boolean | false |
Delete all existing part files and reset the index before importing |
Export
There is no dedicated export() method because the data is already
plain JSON on disk. You have three practical options:
1. Read part files yourself
const fs = require('fs');
const path = require('path');
function exportCollection(collectionPath, outFile) {
const parts = fs.readdirSync(collectionPath)
.filter(f => f.startsWith('part-') && f.endsWith('.json'))
.sort();
const all = [];
for (const part of parts) {
const docs = JSON.parse(fs.readFileSync(path.join(collectionPath, part), 'utf8'));
if (Array.isArray(docs)) all.push(...docs);
}
fs.writeFileSync(outFile, JSON.stringify(all, null, 2));
}
exportCollection('./data/users', './export/users.json');
2. Use find().toArray()
const docs = users.find({}).toArray();
fs.writeFileSync('./export/users.json', JSON.stringify(docs, null, 2));
3. Backup with pack: true
The database backup method can pack every collection into a single
JSON file per collection (see the Backups page).
db.backup('./exports', { pack: true });
// creates ./exports/users/users.json, ./exports/orders/orders.json, …