How to print all keys and values from MongoDB?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I have for instance following records in a collection:

{ "_id" : ObjectId("4f0224ad6f85ce027e000031"), "monday" : "7am" } { "_id" : ObjectId("4f0224ad6f85ce027e00002e"), "tuesday" : "11.40am" } { "_id" : ObjectId("4f0224ad6f85ce027e000025"), "wednestay" : "12am",                                                  "thursday" : "1pm" } 

In the controller I will grab all items and in the view I would like to print them in the shape:

monday 7am tuesday 11.40am wednesday 12am  thursday 1pm 

My app is running on Rails. Exist any quick & elegant way to do it? Thanks!

EDIT this works me:

records = collection.where('something' => variable)  records.each do |rec|   puts rec._id end 

this not

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 

回答1:

You basically don't have to do anything. Just load all records, loop through them, and print.

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!