Question

In ROR and mongoid as a mapper , i came across this class in model:

class StockPrice
 include Mongoid::Document
 include Mongoid::Timestamps

 field :stock_id, type: String
 field :price, type: Float

 index :stock_id => +1, :updated_at => -1

 def self.price(stock_id)
   where(stock_id: stock_id).desc(:updated_at).first.price
 end
def self.crawl(stock_id)
# I am stock price from internet using a web crawler
end
end

As a novice to mongodb, I have following doubts:
1)what index is basically used for?
2)what does this line convey in code:
where(stock_id: stock_id).desc(:updated_at).first.price

Was it helpful?

Solution

Indexing is used in MongoDB the same as with any other database -- it allows rapid access to data records, as well as ordering. For any reasonably large MongoDB database (and MongoDB databases can be HUMONGOUS), indexing is critical for good performance.

Any good MongoDB reference will address indexing.

The +1 and -1 refer to the direction of the fields' values in the index. Thus, updated_at is descending in the index

The where... line provides that that method will return the first record that matches the passed-in stock_id. The records that match stock_id are sorted on updated_at in descending order, so the function will return the latest updated_at value. Note that the index, which was defined as first on stock_id, and then on updated_at in descending order, is optimized to be able to return that value as quickly as possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top