MongoDB
suggest changeMongoDB is a document database: instead of tables and rows it stores collections of JSON-like documents (BSON). Documents in a Dart program map naturally to Map<String, dynamic>, which makes MongoDB easy to use from server-side Dart and command-line tools.
The most widely used driver is the community package mongo_dart. It's pure Dart, async, and supports CRUD operations, query builders, indexes, aggregation pipelines and mongodb+srv:// connection strings for MongoDB Atlas.
Like any database driver, it runs on the Dart VM only. A Flutter app should talk to MongoDB through your own HTTP API, never directly with database credentials shipped in the app.
Setup
Add the dependency to pubspec.yaml:
dependencies:
mongo_dart: ^0.10.3
Run dart pub get. To get a local server for experimenting, the quickest option is Docker:
docker run -d --name mongo -p 27017:27017 mongo:8
Connecting
Db.create() parses the connection string (including mongodb+srv:// URLs, which need a DNS lookup) and open() connects. The database name is the path part of the URL:
import 'package:mongo_dart/mongo_dart.dart';
Future<void> main() async {
final db = await Db.create('mongodb://localhost:27017/shop');
await db.open();
print('connected: ${db.isConnected}, database: ${db.databaseName}');
try {
final names = await db.getCollectionNames();
print('collections: $names');
} finally {
await db.close();
}
}
Output (on an empty database):
connected: true, database: shop
collections: []
Typical connection strings:
mongodb://localhost:27017/shop
mongodb://user:secret@db.example.com:27017/shop?authSource=admin
mongodb+srv://user:secret@cluster0.abcde.mongodb.net/shop?retryWrites=true&w=majority
Read the URL from the environment instead of hard-coding credentials:
import 'dart:io';
final url = Platform.environment['MONGODB_URL'] ?? 'mongodb://localhost:27017/shop';
Open one Db at application startup and share it. It keeps the connection open and multiplexes requests, so you don't need to (and shouldn't) connect per request.
Inserting documents
Get a collection with db.collection(name). Collections and databases are created automatically on the first insert.
import 'package:mongo_dart/mongo_dart.dart';
Future<void> main() async {
final db = await Db.create('mongodb://localhost:27017/shop');
await db.open();
final users = db.collection('users');
await users.drop(); // start fresh for the example
final res = await users.insertOne({
'name': 'Alice',
'email': 'alice@example.com',
'age': 31,
'tags': ['admin', 'beta'],
'address': {'city': 'Paris', 'zip': '75001'},
'createdAt': DateTime.now().toUtc(),
});
print('success: ${res.isSuccess}, inserted: ${res.nInserted}');
print('new _id: ${res.id}');
final many = await users.insertMany([
{'name': 'Bob', 'email': 'bob@example.com', 'age': 25, 'tags': ['beta']},
{'name': 'Carol', 'email': 'carol@example.com', 'age': 42, 'tags': []},
{'name': 'Dave', 'email': 'dave@example.com', 'age': 19},
]);
print('inserted ${many.nInserted} more');
print('count: ${await users.count()}');
await db.close();
}
Output (the _id is different every time):
success: true, inserted: 1
new _id: ObjectId("6710f2a1c3b0d84e2f9a1b11")
inserted 3 more
count: 4
Notes:
- If you don't provide an
_id, the driver generates anObjectId. You can also supply your own_idof any type (string, int, ...), as long as it is unique within the collection. - Documents can nest maps and lists, and different documents in the same collection don't need the same fields (
Davehas notags). DateTimevalues are stored as BSON dates. BSON dates have millisecond precision and no time zone, so store UTC and convert to local time when displaying.
Querying
find() returns a Stream<Map<String, dynamic>>, and findOne() returns a Future of a single document or null. Selectors can be built with the where query builder:
// One document, or null.
final alice = await users.findOne(where.eq('name', 'Alice'));
print(alice?['email']); // alice@example.com
print(alice?['address']['city']); // Paris
final nobody = await users.findOne(where.eq('name', 'Zed'));
print(nobody); // null
// All documents matching a condition, collected into a list.
final adults = await users
.find(where.gte('age', 21).sortBy('age'))
.toList();
for (final u in adults) {
print('${u['name']} ${u['age']}');
}
Output:
alice@example.com
Paris
null
Bob 25
Alice 31
Carol 42
Because find() is a stream, you can process large result sets one document at a time with await for without loading everything into memory:
await for (final u in users.find(where.exists('tags'))) {
print('${u['name']}: ${u['tags']}');
}
Output:
Alice: [admin, beta]
Bob: [beta]
Carol: []
The query builder
where returns a SelectorBuilder. Its methods can be chained, and conditions on different fields are combined with AND:
| Builder | MongoDB equivalent |
|---|---|
where.eq('age', 31) |
{age: 31} |
where.ne('age', 31) |
{age: {$ne: 31}} |
where.gt / gte / lt / lte('age', 30) |
{age: {$gt: 30}} etc. |
where.inRange('age', 20, 40) |
{age: {$gte: 20, $lt: 40}} |
where.oneFrom('name', ['Bob', 'Dave']) |
{name: {$in: [...]}} |
where.exists('tags') |
{tags: {$exists: true}} |
where.match('email', r'@example\.com$') |
{email: {$regex: ...}} |
.sortBy('age', descending: true) |
sort {age: -1} |
.skip(10).limit(5) |
pagination |
.fields(['name', 'age']) |
projection: return only these fields |
.excludeFields(['_id']) |
projection: drop these fields |
Fields in nested documents are addressed with dot notation:
final parisians = await users
.find(where.eq('address.city', 'Paris').fields(['name']).excludeFields(['_id']))
.toList();
print(parisians); // [{name: Alice}]
// The two oldest users, only name and age.
final oldest = await users
.find(where.sortBy('age', descending: true).limit(2).fields(['name', 'age']).excludeFields(['_id']))
.toList();
print(oldest); // [{name: Carol, age: 42}, {name: Alice, age: 31}]
// Array fields match if any element matches.
final betaTesters = await users.find(where.eq('tags', 'beta')).map((u) => u['name']).toList();
print(betaTesters); // [Alice, Bob]
Raw query maps
You can also pass a plain map in MongoDB's query language. This is handy for operators the builder doesn't cover, and when you're translating queries from the MongoDB docs or shell. Use raw strings (r'$or') so Dart doesn't treat $ as string interpolation:
final young = await users.find({
r'$or': [
{'age': {r'$lt': 20}},
{'tags': {r'$size': 0}},
],
}).map((u) => u['name']).toList();
print(young); // [Carol, Dave]
Updating documents
updateOne() changes the first matching document and updateMany() changes all of them. Describe the change with the modify builder (or a raw map of update operators):
// $set and $inc on one document.
var res = await users.updateOne(
where.eq('name', 'Alice'),
modify.set('address.city', 'Lyon').inc('age', 1),
);
print('matched: ${res.nMatched}, modified: ${res.nModified}');
// $push adds to an array, $addToSet adds only if not already present.
await users.updateOne(where.eq('name', 'Bob'), modify.addToSet('tags', 'admin'));
// Update many: remove a field from all teenagers.
// Dave is the only one and has no tags, so nothing is modified.
res = await users.updateMany(where.lt('age', 20), modify.unset('tags'));
print('modified: ${res.nModified}');
// Same as modify.set, written as a raw map.
await users.updateOne(
{'name': 'Carol'},
{r'$set': {'email': 'carol@corp.example.com'}},
);
final alice = await users.findOne(where.eq('name', 'Alice'));
print('${alice!['age']} ${alice['address']}');
Output:
matched: 1, modified: 1
modified: 0
32 {city: Lyon, zip: 75001}
Useful modify operations: set, unset, inc, mul, min, max, rename, push, addToSet, pull, popFirst, popLast, currentDate.
Upserts and replacing
An upsert updates the matching document, or inserts a new one if nothing matches. It's a good fit for counters and "create or update" logic:
final counters = db.collection('counters');
for (var i = 0; i < 3; i++) {
await counters.updateOne(
where.eq('_id', 'page:/home'),
modify.inc('views', 1),
upsert: true,
);
}
print(await counters.findOne(where.eq('_id', 'page:/home')));
// {_id: page:/home, views: 3}
replaceOne() swaps the whole document (except _id) for a new one:
await users.replaceOne(
where.eq('name', 'Dave'),
{'name': 'Dave', 'email': 'dave@example.com', 'age': 20, 'tags': ['new']},
);
Deleting documents
var res = await users.deleteOne(where.eq('name', 'Dave'));
print('removed: ${res.nRemoved}'); // removed: 1
res = await users.deleteMany(where.lt('age', 18));
print('removed: ${res.nRemoved}'); // removed: 0
// Remove every document but keep the collection and its indexes:
// await users.deleteMany({});
// Remove the collection itself:
// await users.drop();
Working with ObjectId
_id values generated by MongoDB are ObjectId instances. To look a document up by an id that came from a URL or JSON, convert the hex string back to an ObjectId; comparing it with the plain string matches nothing:
final doc = await users.findOne(where.eq('name', 'Alice'));
final ObjectId id = doc!['_id'];
final hex = id.oid; // 24-char hex string, e.g. for a REST URL
print(hex.length); // 24
print(id.dateTime); // creation time, encoded in the id itself
final again = await users.findOne(where.id(ObjectId.fromHexString(hex)));
print(again?['name']); // Alice
final wrong = await users.findOne(where.eq('_id', hex));
print(wrong); // null - a String is not an ObjectId
where.id(x) is shorthand for where.eq('_id', x). ObjectId.fromHexString throws on malformed input, so validate user-supplied ids (or catch the error and return 404).
Indexes and unique constraints
Without an index, every query scans the whole collection. Create indexes for fields you filter or sort on. createIndex is idempotent, so it's safe to call at startup:
await users.createIndex(key: 'email', unique: true);
await users.createIndex(keys: {'address.city': 1, 'age': -1});
final dup = await users.insertOne({'name': 'Alice 2', 'email': 'alice@example.com'});
if (dup.isFailure) {
print('code ${dup.writeError?.code}: ${dup.writeError?.errmsg}');
}
Output:
code 11000: E11000 duplicate key error collection: shop.users index: email_1 dup key: { email: "alice@example.com" }
Note that write errors such as duplicate keys are reported in the returned WriteResult rather than thrown, so check isSuccess / isFailure when it matters. Connection problems, on the other hand, are thrown as exceptions.
Aggregation
The aggregation pipeline transforms documents in stages: filter ($match), group and compute ($group), reshape ($project), sort, join ($lookup), and more. Pass the pipeline as a list of maps to aggregateToStream():
final orders = db.collection('orders');
await orders.drop();
await orders.insertMany([
{'customer': 'alice', 'total': 30.0, 'status': 'paid'},
{'customer': 'bob', 'total': 12.5, 'status': 'paid'},
{'customer': 'alice', 'total': 45.0, 'status': 'paid'},
{'customer': 'carol', 'total': 99.0, 'status': 'cancelled'},
{'customer': 'bob', 'total': 7.5, 'status': 'paid'},
]);
final report = await orders.aggregateToStream([
{r'$match': {'status': 'paid'}},
{
r'$group': {
'_id': r'$customer',
'orders': {r'$sum': 1},
'revenue': {r'$sum': r'$total'},
},
},
{r'$sort': {'revenue': -1}},
]).toList();
for (final row in report) {
print('${row['_id']}: ${row['orders']} orders, \$${row['revenue']}');
}
Output:
alice: 2 orders, $75.0
bob: 2 orders, $20.0
Inside a pipeline, r'$customer' (a string starting with $) refers to the value of the customer field, while r'$sum' is an operator name. Raw strings keep both readable.
Mapping documents to classes
Passing Map<String, dynamic> around everywhere gets error-prone. A common pattern is a small model class with fromMap / toMap, the same idea used for JSON:
import 'package:mongo_dart/mongo_dart.dart';
class User {
final ObjectId? id;
final String name;
final String email;
final int? age;
User({this.id, required this.name, required this.email, this.age});
factory User.fromMap(Map<String, dynamic> m) => User(
id: m['_id'] as ObjectId?,
name: m['name'] as String,
email: m['email'] as String,
age: m['age'] as int?,
);
Map<String, dynamic> toMap() => {
if (id != null) '_id': id,
'name': name,
'email': email,
if (age != null) 'age': age,
};
@override
String toString() => 'User($name, $email, age: $age)';
}
class UserRepository {
final DbCollection _coll;
UserRepository(Db db) : _coll = db.collection('users');
Future<ObjectId> add(User u) async {
final res = await _coll.insertOne(u.toMap());
if (res.isFailure) {
throw StateError(res.writeError?.errmsg ?? 'insert failed');
}
return res.id as ObjectId;
}
Future<User?> byEmail(String email) async {
final m = await _coll.findOne(where.eq('email', email));
return m == null ? null : User.fromMap(m);
}
Future<List<User>> olderThan(int age) =>
_coll.find(where.gt('age', age).sortBy('name')).map(User.fromMap).toList();
}
Future<void> main() async {
final db = await Db.create('mongodb://localhost:27017/shop');
await db.open();
try {
final repo = UserRepository(db);
await db.collection('users').drop();
await repo.add(User(name: 'Eve', email: 'eve@example.com', age: 28));
await repo.add(User(name: 'Frank', email: 'frank@example.com', age: 35));
print(await repo.byEmail('eve@example.com'));
print(await repo.olderThan(30));
} finally {
await db.close();
}
}
Output:
User(Eve, eve@example.com, age: 28)
[User(Frank, frank@example.com, age: 35)]
To send such a document to a client as JSON, convert the ObjectId to its hex string (id.oid) and DateTime values to ISO 8601 strings first; jsonEncode doesn't know how to encode them.
Best practices
- Open one
Dband reuse it. Connect at startup, close on shutdown (await db.close()in afinallyblock or a shutdown hook). - Never build queries from untrusted maps. If a user can send
{"$ne": null}where you expected a string, they can bypass filters. Validate types (as String) before putting request data into a selector. - Create indexes for your queries, including unique indexes for things like emails and usernames, and check
WriteResult.isSuccessfor writes that can violate them. - Use projections and
limitto avoid transferring documents and fields you don't need. - Model for your access patterns. Embed data that is read together (an order's line items) and reference data that is shared or grows without bound (a user's orders).
- Store dates in UTC and remember BSON dates only keep milliseconds.
- For multi-document ACID transactions or change streams you need a replica set and a driver that supports them; check the
mongo_dartchangelog for the current state before relying on these features. - For relational data, see Relational databases; for caching in front of MongoDB, see Redis.