Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid Delete Document matching ID

Tags:

ruby

mongoid

I'm trying to remove a duplicate document in my collection. Here's my code:

class Sites
  include Mongoid::Document
  store_in collection: "sites"
end

Sites.destroy_all(conditions: { _id: BSON::ObjectId("5685a45be4b06ab5911dcd12")})

Here's what is returned:

D, [2015-12-31T17:39:16.488657 #10126] DEBUG -- : MONGODB | localhost:27017 | rails.find | STARTED | {"find"=>"sites", "filter"=>{"conditions"=>{"_id"=>BSON::ObjectId('5685a45be4b06ab5911dcd12')}}}
D, [2015-12-31T17:39:16.488946 #10126] DEBUG -- : MONGODB | localhost:27017 | rails.find | SUCCEEDED | 0.000189083s

But when I search the document is still there :(

{"_id"=>BSON::ObjectId('5685a45be4b06ab5911dcd12'), "name"=>"StackOverflow", "title"=>"Stack Overflow", "type"=>"Forum", "url"=>"http://www.stackoverflow.com"}

How do I permanently delete a document by reference using Mongoid?

like image 547
Ken J Avatar asked Dec 24 '22 11:12

Ken J


2 Answers

Mongoid with 5.x follows a lot more closely to the AR methods we are used to so your id field is behaves in a similar way.

Sites.where(id: '5685a45be4b06ab5911dcd12').delete

To have all the necessary callbacks be called as well just use .destroy. Just know this loads everything into memory and can be expensive.

Sites.where(id: '5685a45be4b06ab5911dcd12').destroy
like image 196
JohnnyD Avatar answered Jan 12 '23 17:01

JohnnyD


After doing a lot of iterations this works for me:

Sites.destroy_all({ :_id => BSON::ObjectId('5685a45be4b06ab5911dcd12')})

I've found that Mongoid is not very helpful when troubleshooting. I have to do a lot more trial and error to discover how to do things :(

like image 32
Ken J Avatar answered Jan 12 '23 17:01

Ken J