从一个小栗子开始
class Page include MongoMapper::Document key :title, String key :day_count, Integer, :default => 0 key :week_count, Integer, :default => 0 key :month_count, Integer, :default => 0 key :tags, Array end
1.increment
增加,用来使给定的key增加相应的值
现在数据库里有两条记录,如下:
> db.pages.find()
{ "_id" : ObjectId("50d30cd943ff68149e000001"), "title" : "111111", "day_count" : 2, "week_count" : 3, "month_count" : 5, "tags" : [ ] }
{ "_id" : ObjectId("50d3e9c843ff681964000001"), "title" : "22222222", "day_count" : 2, "week_count" : 4, "month_count" : 6, "tags" : [ ] }
使用increment
test "test increment" do Page.increment({:title => '22222222'}, :day_count => 1, :week_count => 2, :month_count => 3) @page = Page.find_by_title("111111") @page.increment(:day_count => 2, :week_count => 3, :month_count => 5) end再看数据库
jury:unit rui$ mongo MongoDB shell version: 2.2.0 connecting to: test > db.pages.find() { "_id" : ObjectId("50d30cd943ff68149e000001"), "title" : "111111", "day_count" : 4, "week_count" : 6, "month_count" : 10, "tags" : [ ] } { "_id" : ObjectId("50d3e9c843ff681964000001"), "title" : "22222222", "day_count" : 3, "week_count" : 6, "month_count" : 9, "tags" : [ ] } >
2.decrement
就是减去
让我们把上面的数值都减一
test "test decrement" do Page.decrement({:title => '22222222'}, :day_count => 1, :week_count => 1, :month_count => 1) @page = Page.find_by_title("111111") @page.decrement(:day_count => 1, :week_count => 1, :month_count => 1) end end运行后
结果
比如
test "test set" do Page.set({:title => '111111'}, :title => "New111111") end
请仔细比较
另:
@page.set(:title => "New Home") Page.set({:title => 'Home'}, :title => "New Home") Page.set(@page.id, @page2.id, :title => "New Home")
移除
#@page.unset(:title) 这里只演示第二个
Page.unset({:title => 'New111111'}, :title)
#Page.unset(@page.id, @page2.id, :title)
附加一个值到一个数组里
@page.push(:tags => 'foo')
Page.push({:title => 'Home'}, :tags => 'foo')
Page.push(@page.id, @page2.id, :tags => 'foo')
附加若干个值到一个数组里
@page.push_all(:tags => ['foo','bar'])
Page.push_all({:title => 'Home'}, :tags => ['foo','bar'])
Page.push_all(@page.id, @page2.id, :tags => ['foo','bar'])
添加一个唯一的值到数组里
@page.add_to_set(:tags => 'foo')
Page.add_to_set({:title => 'Home'}, :tags => 'foo')
Page.add_to_set(@page.id, @page2.id, :tags => 'foo')
从数组里删除一个值
@page.pull(:tags => 'foo')
Page.pull({:title => 'Home'}, :tags => 'foo')
Page.pull(@page.id, @page2.id, :tags => 'foo')
从数组里删除若干个值
@page.pull_all(:tags => ['foo','bar'])
Page.pull_all({:title => 'Home'}, :tags => ['foo','bar'])
Page.pull_all(@page.id, @page2.id, :tags => ['foo','bar'])
删除数组里最后的元素
@page.pop(:tags => 1)
Page.pop({:title => 'Home'}, :tags => 1)
Page.pop(@page.id, @page2.id, :tags => 1)如果传入的是-1则删除第一个元素