Search code examples
scalamongodbcasbahsalat

How to retrieve all objects in a Mongodb collection including the ids?


I'm using Casbah and Salat to create my own Mongodb dao and am implementing a getAll method like this:

val dao: SalatDAO[T, ObjectId]    
def getAll(): List[T] = dao.find(ref = MongoDBObject()).toList 

What I want to know is:

  1. Is there a better way to retrieve all objects?
  2. When I iterate through the objects, I can't find the object's _id. Is it excluded? How do I include it in the list?

Solution

  • 1°/ The ModelCompanion trait provides a def findAll(): SalatMongoCursor[ObjectType] = dao.find(MongoDBObject.empty) methods. You will have to do a dedicated request for every collection your database have.

    If you iterate over the objects returned, it could be better to iterate with the SalatMongoCursor[T] returned by the dao.find rather than doing two iterations (one with the toList from Iterator trait then another on your List[T]).

    2°/ Salat maps the _id key with your class id field. If you define a class with an id: ObjectId field. This field is mapped with the mongo _id key. You can change this behaviour using the @Key annotation as pointed out in Salat documentation