如何从MongoDB打印所有键和值? [英] How to print all keys and values from MongoDB?
本文介绍了如何从MongoDB打印所有键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我在一个集合中有以下记录:
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
我的应用程序在Rails上运行.存在任何快速&优雅的方式吗?谢谢!
My app is running on Rails. Exist any quick & elegant way to do it? Thanks!
编辑 这对我有效:
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
推荐答案
您基本上不需要执行任何操作.只需加载所有记录,遍历它们,然后打印即可.
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
这篇关于如何从MongoDB打印所有键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文