问题
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:
- Is there a better way to retrieve all objects?
- 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?
回答1:
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
回答2:
I implemented something like:
MyDAO.ids(MongoDBObject("_id" -> MongoDBObject("$exists" -> true)))
This fetches all the ids, but given the wide range of what you might be doing, probably not the best solution for all situations. Right now, I'm building a small system with 5 records of data, and using this to help understand how MongoDB works.
If this was a production database with 1,000,000 entries, then this (or any getAll query) would be stupid. Instead of doing that, consider trying to write a targeted query that goes after the real results you seek.
来源:https://stackoverflow.com/questions/11390625/how-to-retrieve-all-objects-in-a-mongodb-collection-including-the-ids