Well, the title is self-explicative. But, let me elaborate a little better. First of all, I am using Mongoid, a Gem for using MongoDB with rails applications.
#1) I have a large collection, which has information about a map. A map embeds a lot of tiles, and each tile references a terrain collection, a user collection, and has some other information. Therefore, if I obtain all tiles from a map, I will have a really large structure. However, I would like to cache a structure that comprises a matrix with only the terrain information. In order to do that, I select all tiles (and hence, all their unneeded information) and use only the terrain field. How can I select ONLY the terrain field on Mongoid? I tried operating with select on several ways, but I did not manage to do it.. (by the way, just for the sake of exemplification, I access the tiles array with the line "Map.first.tiles").
#2) Well.. I am already here, so, why not ask this. Should I really use the inverse_of fields on my Models? I did not use it anywhere, and everything seems to be working perfectly. I do not see why it is needed, as it is pretty much straight forward to determine where to put them, and what they are the inverse of.
Thanks in advance. Fernando.
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 unset fields and for non-existent fields.
source: https://docs.mongodb.com/ecosystem/tutorial/mongoid-queries/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With