Anonymous avatar Anonymous committed 5b0aeb6

Sample usage for findOne() and remove() filtered by ObjectId

Comments (0)

Files changed (21)

examples/queries.dart

 #import("../lib/mongo.dart");
 #import("dart:builtin");
-main(){
+main(){  
   Db db = new Db("mongo-dart-test");
+  var id;
   DbCollection coll;
   db.open().chain((c){
     print('connection open');
     coll = db.collection("simple_data");
     coll.remove();
+    print('Packing data to insert into collection by Bson...');
     for (var n = 0; n<1000; n++){  
       coll.insert({"my_field":n,"str_field":"str_$n"});
     }      
+    print('Done. Now sending it to MongoDb...');
     return coll.findOne(query().eq("my_field", 17));
   }).chain((val){
-      print("Filtered by my_field= 17} $val");
-      print("Filtered by my_field gt 995}}:");
+      print("Filtered by my_field=17 $val");
+      id = val["_id"];
+      return coll.findOne(query().id(id));
+  }).chain((val){      
+      print("Filtered by _id=$id: $val");    
+      print("Removing doc with _id=$id");
+      coll.remove(query().id(id));
+      return coll.findOne(query().id(id));
+  }).chain((val){      
+      print("Filtered by _id=$id: $val. There more no such a doc");
       return coll.find(query().gt("my_field", 995)).each((v)=>print(v));
   }).chain((val){    
     print("Filtered by my_field gt 700, lte 703");

examples/raw_queries.dart

 main(){
   Db db = new Db("mongo-dart-test");
   DbCollection coll;
+  ObjectId id;
   db.open().chain((c){
     print('connection open');
     coll = db.collection("simple_data");
     }      
     return coll.findOne({"my_field": 17});
   }).chain((val){
-      print("Filtered by {'my_field': 17} $val");
-      print("Filtered {'my_field': {'\$gt': 995}}:");
-      return coll.find({'my_field': {'\$gt': 995}}).each((v)=>print(v));
-  }).chain((val){
+      print("Filtered by my_field=17 $val");
+      id = val["_id"];
+      return coll.findOne({"_id":id});
+  }).chain((val){      
+      print("Filtered by _id=$id: $val");    
+      print("Removing doc with _id=$id");
+      coll.remove({"_id":id});
+      return coll.findOne({"_id":id});
+  }).chain((val){      
+      print("Filtered by _id=$id: $val. There more no such a doc");
       print("Filtered by {'str_field': {'\$regex': new BsonRegexp('^str_(5|7|8)17\$')}");
       return coll.find({'str_field': {'\$regex': new BsonRegexp('^str_(5|7|8)17\$')}}).each((v)=>print(v));        
   }).then((dummy){    

examples/types.dart

       'int':42,
       'float':33.3333,
       'regexp': new BsonRegexp(".?dim"),
-//    'regexp2':/foobar2/,
       'boolean':true,
       'where':new BsonCode('this.x == 3'),
       'null':null
+networking/logger.dart
+bson/bson.dart
+mongo.dart
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>lib</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.google.dart.tools.core.dartBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.google.dart.tools.core.dartNature</nature>
+	</natures>
+</projectDescription>

lib/bson/bson_type.dart

-class ElementPair{
+class _ElementPair{
   String name;
   var value;
-  ElementPair([this.name,this.value]);
+  _ElementPair([this.name,this.value]);
 }
 class BsonObject {  
   int get typeByte(){ throw const Exception("must be implemented");}
   } 
   packValue(var buffer){ throw const Exception("must be implemented");}
 
-  ElementPair unpackElement(buffer){
-    ElementPair result = new ElementPair();
+  _ElementPair unpackElement(buffer){
+    _ElementPair result = new _ElementPair();
     result.name = buffer.readCString();    
     unpackValue(buffer);
     result.value = value;
   unpackValue(var buffer){ throw const Exception("must be implemented");}
   get value()=>null;
 }
-
- int elementSize(name, value) {
-    int size = 1;
-    if (name !== null){
-      size += name.length + 1;
-    } 
-    size += bsonObjectFrom(value).byteLength();
-    return size;
-  }
+int elementSize(name, value) {
+  int size = 1;
+  if (name !== null){
+    size += name.length + 1;
+  } 
+  size += bsonObjectFrom(value).byteLength();
+  return size;
+}
 BsonObject bsonObjectFrom(var value){
   if (value is BsonObject){
     return value;

lib/bson/objectid.dart

   packValue(Binary buffer){
     buffer.bytes.setRange(buffer.offset,12,id.bytes);
     buffer.offset += 12;
- }
+  } 
 }
   }
   
   
-  getNextItem(){
+  Map getNextItem(){
     return items.removeFirst();
   }
-  Future nextObject(){
+  Future<Map> nextObject(){
     if (state == INIT){
-      Completer nextItem = new Completer();
+      Completer<Map> nextItem = new Completer<Map>();
       MongoQueryMessage qm = generateQueryMessage();
       Future<MongoReplyMessage> reply = db.executeQueryMessage(qm);
       reply.then((replyMessage){
         cursorId = replyMessage.cursorId;
         items.addAll(replyMessage.documents);
         if (items.length > 0){
-          nextItem.complete(getNextItem());
+          Map nextDoc = getNextItem();
+          debug("Cursor getNextItem $nextDoc");
+          nextItem.complete(nextDoc);
         }
         else{
           nextItem.complete(null);

Empty file added.

lib/helpers/map_proxy.dart

+class _MapProxy<K,V> implements Map<K,V>{
+  LinkedHashMap map;
+  Queue keys;
+  _MapProxy(): map = {};
+  bool containsValue(V value)=>map.containsValue(value);
+  
+  bool containsKey(K key)=>map.containsKey(key);
+  
+  V operator [](K key)=>map[key];
+  
+  void operator []=(K key, V value){
+   map[key]=value;
+  } 
+
+  V putIfAbsent(K key, V ifAbsent())=>map.putIfAbsent(key, ifAbsent);
+  
+  V remove(K key)=>map.remove(key);
+  
+  void clear()=>map.clear();
+
+  void forEach(void f(K key, V value))=>map.forEach(f);
+  
+  Collection<K> getKeys()=>map.getKeys();
+  
+  Collection<V> getValues()=>map.getValues();
+  
+  int get length() => map.length;
+
+  bool isEmpty()=>map.isEmpty();  
+}

lib/helpers/selector_builder.dart

+SelectorBuilder query(){
+  return new SelectorBuilder();
+}
+class SelectorBuilder<K,V> extends _MapProxy<K,V>{
+  toString()=>"SelectorBuilder($map)";
+  SelectorBuilder eq(String fieldName,value){
+    map[fieldName] = value;
+    return this;
+  }
+  SelectorBuilder id(value){
+    map["_id"] = value;
+    return this;
+  }
+  SelectorBuilder ne(String fieldName, value){
+    map[fieldName] = {"\$ne":value};
+    return this;
+  }
+  SelectorBuilder gt(String fieldName,value){
+    map[fieldName] = {"\$gt":value};
+    return this;
+  }
+  SelectorBuilder lt(String fieldName,value){
+    map[fieldName] = {"\$lt":value};
+    return this;
+  }
+  SelectorBuilder gte(String fieldName,value){
+    map[fieldName] = {"\$gte":value};
+    return this;
+  }
+  SelectorBuilder lte(String fieldName,value){    
+    map[fieldName] = {"\$lte":value};
+    return this;
+  }
+  SelectorBuilder all(String fieldName, List values){
+    map[fieldName] = {"\$all":values};
+    return this;
+  }
+  SelectorBuilder nin(String fieldName, List values){
+    map[fieldName] = {"\$nin":values};
+    return this;
+  }
+  SelectorBuilder oneFrom(String fieldName, List values){
+    map[fieldName] = {"\$in":values};
+    return this;
+  } 
+  SelectorBuilder exists(String fieldName){
+    map[fieldName] = {"\$exists":true};
+    return this;    
+  }
+  SelectorBuilder notExists(String fieldName){
+    map[fieldName] = {"\$exists":false};
+    return this;    
+  }
+  SelectorBuilder mod(String fieldName, int value){
+    map[fieldName] = {"\$mod":[value,0]};
+    return this;    
+  }
+  SelectorBuilder match(String fieldName, String pattern,[bool multiLine, bool caseInsensitive, bool verbose, bool dotAll, bool unicodeMode, bool localeDependent]){    
+    map[fieldName] = {'\$regex': new BsonRegexp('^str_(5|7|8)17\$',multiLine:multiLine, caseInsensitive:caseInsensitive,
+        verbose:verbose, dotAll:dotAll,unicodeMode:unicodeMode,localeDependent:localeDependent)};
+    return this;    
+  }
+  SelectorBuilder range(String fieldName, min, max, [bool minInclude=true, bool maxInclude=true]){
+    Map rangeMap = {};
+    if (minInclude){
+      rangeMap["\$gte"] = min;
+    }
+    else{
+      rangeMap["\$gt"] = min;
+    }
+    if (maxInclude){
+      rangeMap["\$lte"] = max;
+    }
+    else{
+      rangeMap["\$gt"] = max;
+    }
+    map[fieldName] = rangeMap;
+    return this;    
+  }
+  _internQueryMap(){
+    if (!map.containsKey("query")){
+      LinkedHashMap queryMap = new LinkedHashMap.from(map);
+      map.clear();
+      map["query"] = queryMap;
+    }    
+  }
+  SelectorBuilder sortBy(String fieldName, [bool descending=false]){
+    _internQueryMap();
+    if (!map.containsKey("orderby")){
+      map["orderby"] = new LinkedHashMap();  
+    }
+    int order = 1;
+    if (descending){
+      order = -1;
+    }
+    map["orderby"][fieldName] = order;      
+    return this;    
+  }
+  SelectorBuilder comment(String commentStr){
+    _internQueryMap();  
+    map["\$comment"] = commentStr;      
+    return this;    
+  }
+  SelectorBuilder explain(){
+    _internQueryMap();  
+    map["\$explain"] = true;      
+    return this;    
+  }
+  SelectorBuilder snapshot(){
+    _internQueryMap();  
+    map["\$snapshot"] = true;      
+    return this;    
+  }
+  SelectorBuilder showDiskLoc(){
+    _internQueryMap();  
+    map["\$showDiskLoc"] = true;      
+    return this;    
+  }
+  SelectorBuilder returnKey(){
+    _internQueryMap();  
+    map["\$sreturnKey"] = true;      
+    return this;    
+  }  
+}

lib/helpers/utils.dart

+logger() { 
+  Utils.setVerboseState(); 
+  Utils.getLogger();  
+}
+setVerboseState(){
+  Utils.setVerboseState();  
+}
+info(String s){
+  Utils.getLogger().info(s);
+}
+warn(String s){
+  Utils.getLogger().warn(s);
+}
+error(String s){
+  Utils.getLogger().error(s);
+}
+debug(String s){
+  Utils.getLogger().debug(s);
+}
+_loggerBuilder(name) {
+  if(name == "Verbose"){
+    File file = new File("log.txt");
+    if (file.existsSync()){
+      file.deleteSync();  
+    }      
+    return new LoggerImpl(name, debugEnabled: true, errorEnabled:true, infoEnabled:true, warnEnabled:true,appenders:[new FileAppender("log.txt")]); 
+  }         
+  // default logger for the rest
+  return new LoggerImpl(name, debugEnabled: false, errorEnabled:true, infoEnabled:false, warnEnabled:true);
+}
+class Utils{
+  static Logger logger;
+  static Logger getLogger(){
+    if (logger === null){
+      LoggerFactory.builder = _loggerBuilder;      
+      logger = LoggerFactory.getLogger("Runtime");
+    } 
+    return logger;
+  }
+  static setVerboseState(){
+    LoggerFactory.builder = _loggerBuilder;    
+    logger = LoggerFactory.getLogger("Verbose");    
+  }
+}

lib/map_proxy.dart

-class _MapProxy<K,V> implements Map<K,V>{
-  LinkedHashMap map;
-  Queue keys;
-  _MapProxy(): map = {};
-  bool containsValue(V value)=>map.containsValue(value);
-  
-  bool containsKey(K key)=>map.containsKey(key);
-  
-  V operator [](K key)=>map[key];
-  
-  void operator []=(K key, V value){
-   map[key]=value;
-  } 
-
-  V putIfAbsent(K key, V ifAbsent())=>map.putIfAbsent(key, ifAbsent);
-  
-  V remove(K key)=>map.remove(key);
-  
-  void clear()=>map.clear();
-
-  void forEach(void f(K key, V value))=>map.forEach(f);
-  
-  Collection<K> getKeys()=>map.getKeys();
-  
-  Collection<V> getValues()=>map.getValues();
-  
-  int get length() => map.length;
-
-  bool isEmpty()=>map.isEmpty();  
-}
 #source("db.dart");
 #source("dbcollection.dart");
 #source("cursor.dart");
-#source("utils.dart");
-#source("map_proxy.dart");
-#source("selector_builder.dart");
+#source("helpers/utils.dart");
+#source("helpers/map_proxy.dart");
+#source("helpers/selector_builder.dart");

lib/networking/connection.dart

        debug("Buffer not send fully, offset: ${bufferToSend.offset}");
       }
       new Timer(0,(t)=>sendBufferFromTimer());              
+//      sendBuffer("From sendBuffer");
     }        
     else {
       //print("setting onwrite to null");

lib/networking/dbcommand.dart

   static DbCommand createDropDatabaseCommand(Db db) {
     return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null);
   }
+  static DbCommand createQueryDBCommand(Db db, Map command) {
+    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, 1, command, null);
+  }
+  static DbCommand createDBSlaveOKCommand(Db db, Map command) {
+    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT | MongoQueryMessage.OPTS_SLAVE, 0, -1, command, null);
+  }
   
   static DbCommand createPingCommand(Db db) {
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, 1, {'ping':1}, null);
-  }  
+    return createQueryDBCommand(db, {'ping':1});
+  }
   static DbCommand createGetLastErrorCommand(Db db) {
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, 1, {"getlasterror":1}, null);
+    return createQueryDBCommand(db, {"getlasterror":1});
   }  
   static DbCommand createCountCommand(Db db, String collectionName, [Map selector = const {}]) {
     var finalQuery = new Map();

lib/selector_builder.dart

-SelectorBuilder query(){
-  return new SelectorBuilder();
-}
-class SelectorBuilder<K,V> extends _MapProxy<K,V>{
-  toString()=>"SelectorBuilder($map)";
-  SelectorBuilder eq(String fieldName,Comparable value){
-    map[fieldName] = value;
-    return this;
-  }
-  SelectorBuilder ne(String fieldName, Comparable value){
-    map[fieldName] = {"\$ne":value};
-    return this;
-  }
-  SelectorBuilder gt(String fieldName,Comparable value){
-    map[fieldName] = {"\$gt":value};
-    return this;
-  }
-  SelectorBuilder lt(String fieldName,Comparable value){
-    map[fieldName] = {"\$lt":value};
-    return this;
-  }
-  SelectorBuilder gte(String fieldName,Comparable value){
-    map[fieldName] = {"\$gte":value};
-    return this;
-  }
-  SelectorBuilder lte(String fieldName,Comparable value){    
-    map[fieldName] = {"\$lte":value};
-    return this;
-  }
-  SelectorBuilder all(String fieldName, List values){
-    map[fieldName] = {"\$all":values};
-    return this;
-  }
-  SelectorBuilder nin(String fieldName, List values){
-    map[fieldName] = {"\$nin":values};
-    return this;
-  }
-  SelectorBuilder oneFrom(String fieldName, List values){
-    map[fieldName] = {"\$in":values};
-    return this;
-  } 
-  SelectorBuilder exists(String fieldName){
-    map[fieldName] = {"\$exists":true};
-    return this;    
-  }
-  SelectorBuilder notExists(String fieldName){
-    map[fieldName] = {"\$exists":false};
-    return this;    
-  }
-  SelectorBuilder mod(String fieldName, int value){
-    map[fieldName] = {"\$mod":[value,0]};
-    return this;    
-  }
-  SelectorBuilder match(String fieldName, String pattern,[bool multiLine, bool caseInsensitive, bool verbose, bool dotAll, bool unicodeMode, bool localeDependent]){    
-    map[fieldName] = {'\$regex': new BsonRegexp('^str_(5|7|8)17\$',multiLine:multiLine, caseInsensitive:caseInsensitive,
-        verbose:verbose, dotAll:dotAll,unicodeMode:unicodeMode,localeDependent:localeDependent)};
-    return this;    
-  }
-  SelectorBuilder range(String fieldName, Comparable min, Comparable max, [bool minInclude=true, bool maxInclude=true]){
-    Map rangeMap = {};
-    if (minInclude){
-      rangeMap["\$gte"] = min;
-    }
-    else{
-      rangeMap["\$gt"] = min;
-    }
-    if (maxInclude){
-      rangeMap["\$lte"] = max;
-    }
-    else{
-      rangeMap["\$gt"] = max;
-    }
-    map[fieldName] = rangeMap;
-    return this;    
-  }
-  _internQueryMap(){
-    if (!map.containsKey("query")){
-      LinkedHashMap queryMap = new LinkedHashMap.from(map);
-      map.clear();
-      map["query"] = queryMap;
-    }    
-  }
-  SelectorBuilder sortBy(String fieldName, [bool descending=false]){
-    _internQueryMap();
-    if (!map.containsKey("orderby")){
-      map["orderby"] = new LinkedHashMap();  
-    }
-    int order = 1;
-    if (descending){
-      order = -1;
-    }
-    map["orderby"][fieldName] = order;      
-    return this;    
-  }
-  SelectorBuilder comment(String commentStr){
-    _internQueryMap();  
-    map["\$comment"] = commentStr;      
-    return this;    
-  }
-  SelectorBuilder explain(){
-    _internQueryMap();  
-    map["\$explain"] = true;      
-    return this;    
-  }
-  SelectorBuilder snapshot(){
-    _internQueryMap();  
-    map["\$snapshot"] = true;      
-    return this;    
-  }
-  SelectorBuilder showDiskLoc(){
-    _internQueryMap();  
-    map["\$showDiskLoc"] = true;      
-    return this;    
-  }
-  SelectorBuilder returnKey(){
-    _internQueryMap();  
-    map["\$sreturnKey"] = true;      
-    return this;    
-  }
-  
-}

lib/utils.dart

-logger() { 
-  Utils.setVerboseState(); 
-  Utils.getLogger();  
-}
-setVerboseState(){
-  Utils.setVerboseState();  
-}
-info(String s){
-  Utils.getLogger().info(s);
-}
-warn(String s){
-  Utils.getLogger().warn(s);
-}
-error(String s){
-  Utils.getLogger().error(s);
-}
-debug(String s){
-  Utils.getLogger().debug(s);
-}
-_loggerBuilder(name) {
-  if(name == "Verbose"){
-    File file = new File("log.txt");
-    if (file.existsSync()){
-      file.deleteSync();  
-    }      
-    return new LoggerImpl(name, debugEnabled: true, errorEnabled:true, infoEnabled:true, warnEnabled:true,appenders:[new FileAppender("log.txt")]); 
-  }         
-  // default logger for the rest
-  return new LoggerImpl(name, debugEnabled: false, errorEnabled:true, infoEnabled:false, warnEnabled:true);
-}
-class Utils{
-  static Logger logger;
-  static Logger getLogger(){
-    if (logger === null){
-      LoggerFactory.builder = _loggerBuilder;      
-      logger = LoggerFactory.getLogger("Runtime");
-    } 
-    return logger;
-  }
-  static setVerboseState(){
-    LoggerFactory.builder = _loggerBuilder;    
-    logger = LoggerFactory.getLogger("Verbose");    
-  }
-}
+#Mongo-dart - MongoDB driver for Dart programming language.
+
+It is server-side library with minimalistic support of MongoDb. At the moment supported basic CRUD operations.
+
+Some samples are in directory **examples**. Also Chris Buckett gave a realistic use case scenario in two part blog post:
+
+ - [Building a client / server Dart App – Part 1 – server side](http://dartwatch.com/index.php/2012/03/building-a-client-server-dart-app-part-1-server-side/)
+ - [Building a client / server Dart App – Part 2 – client (browser) side](http://dartwatch.com/index.php/2012/03/building-clientserver-app-part2/)
+
+Project uses libraries:
+
+ - unittest_vm - Bygone version from dart repository
+ - [log4dart](https://github.com/Qalqo/log4dart)

tests/SelectorBuilderTest.dart

 #import("dart:builtin");
 #import('../third_party/testing/unittest/unittest_vm.dart');
 testSelectorBuilderCreation(){
-  SelectorBuilder selector = where();
+  SelectorBuilder selector = query();
+  expect(selector is Map && selector.isEmpty()).isTrue();
+}
+testSelectorBuilderOnObjectId(){
+  ObjectId id = new ObjectId();
+  SelectorBuilder selector = query().eq("_id":);
   expect(selector is Map && selector.isEmpty()).isTrue();
 }
 

third_party/log4dart/FileAppender.dart

  *
  * Note to use this appender you must import dart:io
  */
-class FileAppender {
+class FileAppender implements Appender{
   final String _path;
   
   FileAppender(this._path);
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.