从mongoDB中删除文档

这可能是一个非常愚蠢的问题,但我是MongoDB的新手,所以请耐心等待。 我创建了一个独立的ruby类:

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.destroy => true >> Twit.all => [#] 

那么如何销毁MongoDB中的文档呢? 我究竟做错了什么?

想象一下,您要删除所有带有“name”字段的文档。 所以这是代码:

 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 

不知道ruby,但是使用命令行shell它是:

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

感谢您对此问题的所有帮助。 对于有这个问题的其他人,我相信这是因为我忘了将mongodb二进制文件的位置添加到$PATH变量

在我的例子中,在/usr/local/mongodb/bin安装了二进制文件,我需要将export PATH=/usr/local/mongodb/bin:$PATH到我的~/.bash_profile

使用此代码按ID删除文档:

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