Make room for your data.
Create, read, update and delete BSON documents with the MongoDB collection API.
Get a collection
await BsonLite.connect('myapp');
const notes = BsonLite.collection('notes');The examples below run inside an async function after connection. Collections are created by normal MongoDB writes as needed. BsonLite.collection returns a MongoDB driver Collection, rather than a separate query language.
Create documents
const result = await notes.insertOne({
title: 'Build something useful',
tags: ['project', 'idea'],
done: false,
createdAt: new Date()
});
const id = result.insertedId;
await notes.insertMany([
{ title: 'Write the docs', done: false },
{ title: 'Try the starter', done: true }
]);MongoDB supplies an ObjectId when you omit _id. insertOne returns a write result, not the inserted document. Choose allowed fields when accepting application input.
Read documents
const note = await notes.findOne({ _id: id });
const latest = await notes
.find({ done: false }, { projection: { title: 1, createdAt: 1 } })
.sort({ createdAt: -1 })
.limit(20)
.toArray();
const pending = await notes.countDocuments({ done: false });Use findOne for a document or null. find returns a cursor; apply sort, limit and projection before toArray. Large collections should be paginated rather than loaded into one array.
Update and delete
await notes.updateOne(
{ _id: id },
{ $set: { done: true }, $currentDate: { updatedAt: true } }
);
await notes.deleteOne({ _id: id });
// deleteMany({}) deletes every document. Require a deliberate filter.
The SDK provides database authentication and encrypted storage. Your application still decides who may read or change records. Do not pass an untrusted request body straight into a filter or update document.
Documentation for BsonLite 0.6.0-rc.1. View SDK source · Download the validated SDK