问题
This might be a really stupid question, but I'm new to MongoDB, so bear with me. I've created a stand alone ruby class:
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
...
Then I do the following with 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">]
So how do I destroy documents in MongoDB? What am I doing wrong?
回答1:
Imagine, that you want to delete all the document with empty "name"-field. So here is the code for it:
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
回答2:
Dont know about ruby, but with the command line shell it is:
db.Twit.remove({_id: '4df2d4a0c251b2754c000001'});
回答3:
Thanks for all the help on this issue. For anyone else who has this problem, I believe it is because I forgot to add the the location of the mongodb binary files to the $PATH
variable
In my case installed the binary files in /usr/local/mongodb/bin
as such I needed to add export PATH=/usr/local/mongodb/bin:$PATH
to my ~/.bash_profile
回答4:
Use this code to delete document by ID:
collection.remove({"_id" => BSON::ObjectId("4df2d4a0c251b2754c000001")})
来源:https://stackoverflow.com/questions/6314139/delete-document-from-mongodb