Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从MongoDB打印所有键和值?_Ruby_Ruby On Rails 3_Mongodb_Key - Fatal编程技术网

Ruby 如何从MongoDB打印所有键和值?

Ruby 如何从MongoDB打印所有键和值?,ruby,ruby-on-rails-3,mongodb,key,Ruby,Ruby On Rails 3,Mongodb,Key,例如,我在一个集合中有以下记录: { "_id" : ObjectId("4f0224ad6f85ce027e000031"), "monday" : "7am" } { "_id" : ObjectId("4f0224ad6f85ce027e00002e"), "tuesday" : "11.40am" } { "_id" : ObjectId("4f0224ad6f85ce027e000025"), "wednestay" : "12am",

例如,我在一个集合中有以下记录:

{ "_id" : ObjectId("4f0224ad6f85ce027e000031"), "monday" : "7am" }
{ "_id" : ObjectId("4f0224ad6f85ce027e00002e"), "tuesday" : "11.40am" }
{ "_id" : ObjectId("4f0224ad6f85ce027e000025"), "wednestay" : "12am", 
                                                "thursday" : "1pm" }
在控制器中,我将抓取所有项目,在视图中,我希望将它们打印在形状中:

monday 7am
tuesday 11.40am
wednesday 12am  thursday 1pm
我的应用程序正在Rails上运行。有没有快速优雅的方法?谢谢

编辑 这让我很工作:

records = collection.where('something' => variable)

records.each do |rec|
  puts rec._id
end
这不是

records = collection.where('something' => variable)

records.each do |rec|
  rec.each do |k, v| #here is the error "undefined each"
    next if k == '_id' # skip the _id field
    puts "#{k} #{v}"
  end
end

你基本上什么都不用做。只需加载所有记录,循环浏览并打印即可

records = collection.find()

records.each do |rec|
  rec.attributes.each do |k, v|
    next if k == '_id' # skip the _id field
    puts "#{k} #{v}"
  end
end

谢谢你的评论,我仍然在尝试你的想法,但是我得到了错误
未定义的方法
each'for#`,当然是数据库表中的数据。我在
rec.each do | k,v |
一行中得到了这个错误。只是一个注释:我使用了
find()
method
where
更新了答案。现在检查一下。@user3206440:我想
属性
来自mongoid。而来自驱动程序的原始文档必须具有用于此目的的其他内容。如果使用
mongo
driver,则可以使用
rec.keys.each do | k |
而不是
rec.attributes.each do | k,v |
在上面的答案中