Mongoid on RoR3: 1) how to return specific field on query? 2) what inverse_of is needed for? Mongoid on RoR3: 1) how to return specific field on query? 2) what inverse_of is needed for? mongodb mongodb

Mongoid on RoR3: 1) how to return specific field on query? 2) what inverse_of is needed for?


In general, to only select 1 or more attributes in a mongoid query:

Map.only(:name).all

I wouldn't bother with inverse_only except when Mongoid needs help figuring out the classes. In general, not needed.

If you need to only return certain attributed on an embedded document, you'll want to use the full-path:

Map.first.tiles => [#<Tile _id: 4e1e486042f5bc06e7000002, name: "Earth", distance: 34>]Map.only("tiles.name").first.tiles => [#<Tile _id: 4e1e488742f5bc06e7000003, name: "Earth", distance: nil>]


You can also use pluck

Criteria#pluck

Band.all.pluck(:name)

Get all the values for the provided field. Returns nil for unsetfields and for non-existent fields.

source: https://docs.mongodb.com/ecosystem/tutorial/mongoid-queries/