From 7de404c8e37849ab06da0b0e5e6332376f8a0798 Mon Sep 17 00:00:00 2001 From: Jim Menard Date: Mon, 9 Feb 2009 09:46:30 -0500 Subject: [PATCH] Added Collection#find_first. --- lib/mongo/collection.rb | 8 ++++++++ tests/mongo-qa/stress1 | 4 +--- tests/test_db.rb | 4 ++-- tests/test_db_api.rb | 12 ++++++++++++ 4 files changed, 23 insertions(+), 5 deletions(-) mode change 100644 => 100755 tests/mongo-qa/stress1 diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index 633e95c..d0b3ca4 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -65,6 +65,14 @@ module XGen @db.query(self, Query.new(selector, fields, offset, limit, sort, hint)) end + # Find the first record that matches +selector+. See #find. + def find_first(selector={}, options={}) + cursor = find(selector, options) + obj = cursor.next_object + cursor.close + obj + end + # Insert +objects+, which are hashes. "<<" is aliased to this method. # Returns either the single inserted object or a new array containing # +objects+. The object(s) may have been modified by the database's PK diff --git a/tests/mongo-qa/stress1 b/tests/mongo-qa/stress1 old mode 100644 new mode 100755 index 1b7fdf1..345151b --- a/tests/mongo-qa/stress1 +++ b/tests/mongo-qa/stress1 @@ -22,9 +22,7 @@ n1.times { |i| puts n2.times { |i| - cursor = c.find({:id => i}) - x = cursor.next_object - cursor.close + x = c.find_first({:id => i}) x['subarray'] = "foo#{i}" p x c.modify({:id => i}, x) diff --git a/tests/test_db.rb b/tests/test_db.rb index bb6033d..7ba7804 100644 --- a/tests/test_db.rb +++ b/tests/test_db.rb @@ -67,14 +67,14 @@ class DBTest < Test::Unit::TestCase # new id gets added to returned object obj = coll.insert('name' => 'Fred', 'age' => 42) - row = coll.find({'name' => 'Fred'}, :limit => 1).next_object + row = coll.find_first({'name' => 'Fred'}, :limit => 1) oid = row['_id'] assert_not_nil oid assert_equal obj, row oid = XGen::Mongo::Driver::ObjectID.new obj = coll.insert('_id' => oid, 'name' => 'Barney', 'age' => 41) - row = coll.find({'name' => 'Barney'}, :limit => 1).next_object + row = coll.find_first({'name' => 'Barney'}, :limit => 1) db_oid = row['_id'] assert_equal oid, db_oid assert_equal obj, row diff --git a/tests/test_db_api.rb b/tests/test_db_api.rb index 255c29a..eb55c91 100644 --- a/tests/test_db_api.rb +++ b/tests/test_db_api.rb @@ -216,6 +216,18 @@ class DBAPITest < Test::Unit::TestCase assert_equal 4, docs.size end + def test_find_first + x = @@coll.find_first('a' => 1) + assert_not_nil x + assert_equal 1, x['a'] + end + + def test_find_first_no_records + @@coll.clear + x = @@coll.find_first('a' => 1) + assert_nil x + end + def test_drop_collection assert @@db.drop_collection(@@coll.name), "drop of collection #{@@coll.name} failed" assert !@@db.collection_names.include?(@@coll_full_name)