user160917
user160917

Reputation: 9350

Delete document from mongoDB

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?

Upvotes: 4

Views: 5683

Answers (4)

Use this code to delete document by ID:

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

Upvotes: 0

makaroni4
makaroni4

Reputation: 2281

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

Upvotes: 4

user160917
user160917

Reputation: 9350

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

Upvotes: 0

Geoffrey
Geoffrey

Reputation: 11353

Dont know about ruby, but with the command line shell it is:

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

Upvotes: 0

Related Questions