mongo_dart 0.3.5

  • Installing
  • Versions
  • 85

Mongo-dart - MongoDB driver for Dart programming language. #

Pub Build Status

Server-side driver library for MongoDb implemented in pure Dart.

Basic usage #

Obtaining connection #

  Db db = new Db("mongodb://localhost:27017/mongo_dart-blog");

Querying #

Method find returns stream of maps and accept query parameters, usually build by fluent API query builder provided by mongo_dart_query as top level getter where

  var coll = db.collection('user');
  await coll.find("age", 18)).toList();
  await coll
      .find("my_field", 995).sortBy('my_field'))
      .forEach((v) => print(v));
  await coll.find(where.sortBy('itemId').skip(300).limit(25)).toList();

Method findOne take the same parameter and returns Future of just one map (mongo document)

  val = await coll.findOne(where.eq("my_field", 17).fields(['str_field','my_field']));

Take notice in these samples that unlike mongo shell such parameters as projection (fields), limit and skip are passed as part of regular query through query builder

Inserting documents #

  await usersCollection.insertAll([
    {'login': 'jdoe', 'name': 'John Doe', 'email': ''},
    {'login': 'lsmith', 'name': 'Lucy Smith', 'email': ''}

Updating documents #

You can update whole document with method save

  var v1 = await coll.findOne({"name": "c"});
  v1["value"] = 31;

or you can perform field level updates with method update and top level getter modify for ModifierBuilder fluent API

  coll.update(where.eq('name', 'Daniel Robinson'), modify.set('age', 31));

Removing documents #

  /// or, to remove all documents from collection

Simple app on base of [JSON ZIPS dataset] (

import 'package:mongo_dart/mongo_dart.dart';

main() async {
  void displayZip(Map zip) {
        'state: ${zip["state"]}, city: ${zip["city"]}, zip: ${zip["id"]}, population: ${zip["pop"]}');
  Db db =
      new Db("mongodb://");
  var zips = db.collection('zip');
******************** Zips for state NY, with population between 14000 and 16000,
******************** reverse ordered by population''');
  await zips
          .eq('state', 'NY')
          .inRange('pop', 14000, 16000)
          .sortBy('pop', descending: true))
  print('\n******************** Find ZIP for code 78829 (BATESVILLE)');
  var batesville = await zips.findOne(where.eq('id', '78829'));
  print('******************** Find 10 ZIP closest to BATESVILLE');
  await zips
      .find(where.near('loc', batesville["loc"]).limit(10))
  print('closing db');
  await db.close();

See also #

#Recent change notes

0.3.5 #

  • Upgraded uuid constraint to ^2.0.0.

0.3.4 #

0.3.2 #

  • Cast fixes, for compatibility with Dart 2.
  • Moved from dart:convert usage to package:dart2_constant, for the sake of backwards compatibility.

0.3.1 #

  • Changed the signature of DbCollection.remove; its selector parameter is now required, while writeConcern is now a named optional parameter.
Future remove(selector, {WriteConcern writeConcern});

Resolves #73.


  • Strong mode compliance. Preparing for Dart 2.0


  • Fix bad type in _Connection class


  • Minor changes, commented out code removed
  • Big chunk of tests was commented out in 0.2.6 by error. All tests restored.


  • update for new sdk (with 1.17.0 [MongoMessageHandler] was broken in checked mode)
  • upgrade to current version of crypto package, and it's new (Converter based) API


  • Fixed markdown for pub.


  • Moved mongo_dart project to a new organization on GitHub.
  • Authentication schemes now use Secure Random coming from dart:math since 1.14. ** Note that this version now required SDK version >= 1.14 because of this **
  • Added sort by text score to the query builders.


  • SCRAM-SHA1 authentication scheme added by Joel Trottier-Hebert. Random string (salt) is generated with standard dart Random, which is not cryptographically strong for now, hence beta marker on version.
    Secure Random is due in the next version of SDK, so that would be improved soon.
  • SCRAM-SHA1 scheme used as a default while driver is connected to mongodb 3.0, MONGODB_CR used otherwise. authMechanism connection string option can be used to override these defaults.
  • authSource connection string option added See:
  • Many refactorings in tests and code with async/await done by Joel Trottier-Hebert
  • Dependency on logging package loosen to >=0.9.1 <0.12.0


  • Small bump up in dependencies


  • Swithed to travis from
  • Can use null-aware operators in example (blog)


  • Loosening parameter type in CursorStream in accordance with sdk 1.13.0
  • README update with basic usage


  • Fix issue 71 - Logger allocates lot of strings


  • Breaking change: DbCollection find method now returns Stream<Map> instead of Cursor. Cursor have had compatible with Stream<Map> toList and forEach quite some time already, so in case you used these methods only, you should be covered. On the other hand if you used find().stream to get a stream it is not valid anymore. In that case you should change your code to plain find()
  • Breaking change: This version use upgraded version of bson. ObjectId.toJson now converts ObjectId to simple hex string representation. Earlier it was something like ObjectId('a29d3ae24...aa') New behaviour would be more useful when you serialize bson map to json be default conversion. With new behaviour serialized ObjectId value could be passed to ObjecdId.parse method. But if your code currently depends on old behaviour (if you now use something like id.substring(10, 34) to get hex part of the string representation, you should change your code.


  • compatibility with MongoDB 3.0 and WiredTiger. New db.getCollectionNames(), db.getCollectionInfos(), collection.getIndexes() methods, backward compatible with earlier versions of MongoDb.
  • collectionsInfoCursor, listCollections, indexInformation methods of Db deprecated
  • use test instead of unittest package
  • add code coverage metrix with



  • Remove validation for index keys.


  • Tailable cursor support added by sestegra. See tailable_cursor.dart in example directory.
  • Preliminary support for streaming in Aggregate framerork. Added method aggregateToStream
  • Added getBuildInfo command


  • Additional checks and descriptive error message against opening db in opening state, additional tests


  • Additional checks and descriptive error message against querying closed db



  • Better error handling when a connection with the database is lost. Thanks to luizmineo PR 50.
  • Future(List<String>) listCollections() helper added to Db
  • Future(List<String>) listDatabases() helper added to Db


  • Better error handling. Bugfix for issue 49


  • Initial support for replica set added by sestegra


  • Change log made compatible with pub site preferences, thanks to Andreas Olund.
  • API docs generation set up as hop task.



  • Ready for Dart 1.0


  • adding multiupdate support


  • Upgrade for Dart SDK version


  • Meta lib removed.


  • Upgrade for braking changes in dart:async (StreamEventTransformed removed from API). Ready for Dart SDK version


  • Version contraints removed from pubspec


  • Merge pull request from analogic. Added Future to save and removed unnecessary completers


  • Bugfix for count() method


  • New sample added. Readme rewritten.


  • Network data packets to MongoDb messages conversion refactored.


  • each() method is deprecated in favor of foEach(), so Cursor have more stream-like interface.
  • stream getter added to Cursor. After deprecation period find() will return Stream<Map> instead of Cursor


  • Added support for modifier builder for field level updates. See example/update.dart and testFieldLevelUpdateSimple


  • Updgrate for Dart SDK version (? operator removed)




  • Upgrade for Dart SDK version


  • Query API supports logical AND and OR operators.


  • Bugfix to fields() issue . Fields clause in find(), findOne() methods did not work. Relevant test and sample (in example/query.dart) added


  • Update for changed SelectorBuilder


  • mongo_dart_query published separately and added as dependency to mongo_dart. Unified SelectorBuilder will be used by mongo_dart and objectory.


  • Bson library published separately and added as dependency to mongo_dart


  • Upgrade in Bson for changed implementation of dart:typeddata in Dart SDK version


  • Upgrade for M4.


  • Switch from dart:scalarlist to dart:typeddata. Logging updated to new API.



  • Bug fix for unitialized BsonPlatform


  • Bug fix for MongoMessage header curruption


  • Support for dart SDK version


  • Support for Dart Editor version 0.4.1_r19425


  • GridFS refactored, now works on all old and added tests.


  • GridFS still broken, but in this version there is no malformed types from previous dart:io version


  • Support of dart:io version 2. (Stream-based).
  • [WriteConcern] ( introduced. method has writeConcern param, as individual modifying operations. Default writeConcern = WriteConcern.AKNOWLEDGED
  • writeConcern parameter replaced safeMode parameter on modifying operations
  • GridFS not yet ported to dart:io version 2.


  • Fixed bug in limit functionality. Corresponding test added.


  • M3 ready. Run on version


  • New syntax cleanUp. Next revisions will be published on No more need to use git dependency for dependend application.


  • Ted Sander joined project and added initial support of GridFS functionality


  • Fixed bux in database_tests.dart (Process did not ends cleanly)
  • Sdk package dependencies moved to


  • new syntax changes
  • Selector API changed
  • modifier_builder added


  • Repairing incomplete commit v0.0.5


  • DbCollection's update and insert methods got optional safeMode parameter
  • $err field set in MongoDB result object raises Error in mongo_dart
  • Db got createIndex and ensureIndex methods
  • Feature checklist added.


  • code updates for SDK r14458


  • Changes reflecting dart lib changes - methods to getters, such as String.charCodes(), Map.getKeys() and so on
  • New rules for optional function parameters applied
  • Tests reworked. Got rid of asyncTest. Use expectAsync1 within future chain() and then() methods.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  mongo_dart: ^0.3.5

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:mongo_dart/mongo_dart.dart';
Version Uploaded Documentation Archive
0.3.5 Apr 17, 2019 Go to the documentation of mongo_dart 0.3.5 Download mongo_dart 0.3.5 archive
0.3.4 Dec 19, 2018 Go to the documentation of mongo_dart 0.3.4 Download mongo_dart 0.3.4 archive
0.3.3 Jul 28, 2018 Go to the documentation of mongo_dart 0.3.3 Download mongo_dart 0.3.3 archive
0.3.2 Jun 30, 2018 Go to the documentation of mongo_dart 0.3.2 Download mongo_dart 0.3.2 archive
0.3.1 Oct 24, 2017 Go to the documentation of mongo_dart 0.3.1 Download mongo_dart 0.3.1 archive
0.3.0 Jul 23, 2017 Go to the documentation of mongo_dart 0.3.0 Download mongo_dart 0.3.0 archive
0.2.10 Oct 4, 2016 Go to the documentation of mongo_dart 0.2.10 Download mongo_dart 0.2.10 archive
0.2.9 Jul 15, 2016 Go to the documentation of mongo_dart 0.2.9 Download mongo_dart 0.2.9 archive
0.2.8 Jun 24, 2016 Go to the documentation of mongo_dart 0.2.8 Download mongo_dart 0.2.8 archive
0.2.7 Jun 10, 2016 Go to the documentation of mongo_dart 0.2.7 Download mongo_dart 0.2.7 archive

All 68 versions...

Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Apr 25, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.2.0
  • pana: 0.12.14


Detected platforms: Flutter, other

Primary library: package:mongo_dart/mongo_dart.dart with components: io.

Health suggestions

Fix lib/src/database/db.dart. (-8.17 points)

Analysis of lib/src/database/db.dart reported 17 hints, including:

line 3 col 1: Prefer using /// for doc comments.

line 7 col 3: Prefer using /// for doc comments.

line 19 col 3: Prefer using /// for doc comments.

line 24 col 3: Prefer using /// for doc comments.

line 30 col 3: Prefer using /// for doc comments.

Fix lib/src/database/dbcollection.dart. (-3.93 points)

Analysis of lib/src/database/dbcollection.dart reported 8 hints, including:

line 7 col 46: Use ; instead of {} for empty constructor bodies.

line 43 col 19: Use = to separate a named parameter from its default value.

line 44 col 23: Use = to separate a named parameter from its default value.

line 62 col 3: Prefer using /// for doc comments.

line 83 col 3: Prefer using /// for doc comments.

Fix lib/src/database/cursor.dart. (-1.49 points)

Analysis of lib/src/database/cursor.dart reported 3 hints:

line 116 col 13: Use isNotEmpty instead of length

line 124 col 39: Use isNotEmpty instead of length

line 134 col 13: Use isNotEmpty instead of length

Fix additional 7 files with analysis or formatting issues. (-4.99 points)

Additional issues in the following files:

  • lib/src/gridfs/grid_in.dart (3 hints)
  • lib/src/network/connection.dart (2 hints)
  • lib/src/database/dbcommand.dart (1 hint)
  • lib/src/database/mongo_reply_message.dart (1 hint)
  • lib/src/gridfs/grid_file.dart (1 hint)
  • lib/src/gridfs/gridfs.dart (1 hint)
  • lib/src/network/connection_manager.dart (1 hint)

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Maintain an example.

None of the files in the package's example/ directory matches known example patterns.

Common filename patterns include main.dart, example.dart, and mongo_dart.dart. Packages with multiple examples should provide example/

For more information see the pub package layout conventions.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.69.3 <3.0.0
bson ^0.3.2 0.3.2
collection ^1.14.11 1.14.11
crypto ^2.0.6 2.0.6
logging ^0.11.3+2 0.11.3+2
mongo_dart_query ^0.3.2 0.3.2
path ^1.6.2 1.6.2
pool ^1.4.0 1.4.0
uuid ^2.0.0 2.0.1
Transitive dependencies
async 2.2.0
charcode 1.1.2
convert 2.1.1
fixnum 0.10.9
more 1.16.0
stack_trace 1.9.3
typed_data 1.1.6
Dev dependencies
test ^1.3.0