Commits

Liam Staskawicz committed aabf62d

* Cursor.sort() and test

Comments (0)

Files changed (2)

       throw MongoOpErr("count() failed - $res")
   }
   
-  // This sort()
-  // {
-  //   return this
-  // }
+  **
+  ** Sort the results of this query on the given fields.
+  ** The Int value for each field specifies the sort direction, 
+  ** either ascending (1) or descending (-1).  Other values are invalid.
+  **
+  This sort(Str:Int fields)
+  {
+    if (![1, -1].containsAll(fields.vals))
+      throw ArgErr("sort direction can only be ascending (1) or descending (-1)")
+    opts["order"] = fields
+    return this
+  }
   
   **
   ** Return an explanation of how this Cursor's query will be executed,
     Str:Obj special := [:] { ordered = true }
     if(opts.containsKey("explain"))
       special["\$explain"] = true
+    if(opts.containsKey("order"))
+      special["orderby"] = opts["order"]
     // todo snapshot, hint and order
     return special
   }

test/CursorTest.fan

     
     coll.drop
   }
+  
+  Void testSort()
+  {
+    coll := db["sorttest"]
+    coll.drop
+    20.times { coll.insert(["val":Int.random]) }
+    
+    verifyErr(ArgErr#) { coll.find().sort(["val":111]) }
+    
+    c := coll.find().sort(["val":1])
+    previous := c.next["val"]
+    verify(c.more)
+    while(c.more) {
+      current := c.next["val"]
+      if(current < previous)
+        fail()
+      previous = current
+    }
+    
+    // check descending
+    c = coll.find().sort(["val":-1])
+    previous = c.next["val"]
+    verify(c.more)
+    while(c.more) {
+      current := c.next["val"]
+      if(current > previous)
+        fail()
+      previous = current
+    }
+    
+    coll.drop
+  }
 
 }