2011-06-11 152 views
4

這可能是一個非常愚蠢的問題,但我是MongoDB的新手,請耐心等待。我創建了一個獨立的Ruby類:從mongoDB中刪除文檔

require 'rubygems' 
require 'mongo' 

require 'bson' 
require 'mongo_mapper' 

MongoMapper.database = "testing" 

class Twit 
    include MongoMapper::Document 

    key :id,   Integer, :unique => true 
    key :screen_name, String, :unique => true 

... 

那我該用IRB

>> twit = Twit.all.first 
=> #<Twit _id: BSON::ObjectId('4df2d4a0c251b2754c000001'), id: 21070755, screen_name: "bguestSB"> 
>> twit.destroy 
=> true 
>> Twit.all 
=> [#<Twit _id: BSON::ObjectId('4df2d4a0c251b2754c000001'), id: 21070755, screen_name: "bguestSB">] 

以下那麼,如何銷燬文件在MongoDB中?我究竟做錯了什麼?

+0

抱歉,我不能有更多的幫助。 – 2011-06-11 05:08:53

+0

如果你'Twit.find('4df2d4a0c251b2754c000001')。destroy'然後'Twit.all'會發生什麼? – 2011-06-11 05:13:41

+0

@mu,條目似乎仍然存在。我能夠擺脫保存在數據庫中的文件的唯一方法是刪除整個數據庫。有沒有什麼方式可以阻止我的系統被刪除? – Intentss 2011-06-13 18:02:13

回答

0

感謝在這個問題上的一切幫助。對於其他人誰都有這個問題,我相信這是因爲我忘了在我的案例中/usr/local/mongodb/bin安裝二進制文件MongoDB的二進制文件的位置添加到$PATH變量

因此我需要添加export PATH=/usr/local/mongodb/bin:$PATH到我的~/.bash_profile

0

不知道關於Ruby,但與命令行shell,它是:

db.Twit.remove({_id: '4df2d4a0c251b2754c000001'}); 
4

想象一下,您要刪除所有具有空的「名稱」字段的文檔。因此,這裏是它的代碼:

require 'rubygems' 
require 'mongo' 

db = Mongo::Connection.new("localhost").db("db_name") 
coll = db.collection("coll_name") 

coll.find({:name => ""}).each do |empty_doc| 
    coll.remove(empty_doc) 
end 
0

使用此代碼通過ID刪除文件:

collection.remove({"_id" => BSON::ObjectId("4df2d4a0c251b2754c000001")})