How can I get all field names of the Mongoid Document?
Mongoid already provides you the attributes for an object:
Model.new.attributes
To get the names for these attributes:
Model.fields.keys
How get all column names of model in Mongoid
Use
Model.fields.keys
Replace Model with your model name
Listing fields in a mongodb object
MongoDB has a schema-less design, which means that any document could have different fields contained within it from any other document. To get an exhaustive list of all the fields for all the documents, you would need to traverse all the documents in the collection and enumerate each field. For any reasonably sized collection this is going to be an extremely expensive operation.
There are a couple of helpers that make this more simple: Variety and schema.js . They both allow you to limit the documents inspected, and they report on coverage as well. Both amount to doing a map/reduce on the collections, but are at least simpler than having to write one yourself.
Finding all documents in a collection with Mongoid
Category
indeed doesn't have a method each
because it's a model class, not a collection. It has, however, several methods that do return collection-like objects. One of them is all
. So the code should look like this:
Category.all.each do |test|
puts test.inspect
end
Get names of all keys in the collection
You could do this with MapReduce:
mr = db.runCommand({
"mapreduce" : "my_collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "my_collection" + "_keys"
})
Then run distinct on the resulting collection so as to find all the keys:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
Mongoid - getting all attributes including embedded documents
Since embedded documents are really just other attributes on the parent document, you can get to them like so:
person = Person.create
person.phone_numbers.create(:number => "123-456-7890")
person.attributes
# => {"_id"=>"4c48ff26f7e2da3704000001",
# "phone_numbers"=>
# [{"number"=>"123-456-7890", "_id"=>"4c48ff26f7e2da3704000002"}]}
Mongoid: find all children documents of multiple parent documents
You can use organization_id.in
@locations = Location.where(:organization_id.in => orgs.map(&:id))
Related Topics
Iterate Every Month with Date Objects
How to Get Request.Uri in Model in Rails
Get Substring After the First = Symbol in Ruby
Rails -- Create and Create! Methods, Ror 3 Tutorial
How to Use Nokogiri to Parse an Xml File
Starting or Restarting Unicorn with Capistrano 3.X
How to Get Searchlogic to Work with Rails 3
How to Test 'Create' Controller Actions
How to Use "Gets" on a Rake Task
Rails Convert String to Number
Rails: How to Autocomplete Search for Name But Save Id
How to Recompile a Ruby with Rvm
Can Not Install JSON Gem with Ruby 2.2.3 on Ubuntu
How to Write Specs for Code That Depends on Environment Variables