How to print all keys and values from MongoDB?

2019-06-12 15:10发布

问题:

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