How to retrieve all objects in a Mongodb collectio

2020-07-17 02:36发布

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?

2条回答
对你真心纯属浪费
2楼-- · 2020-07-17 02:43

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.

查看更多
戒情不戒烟
3楼-- · 2020-07-17 03:01

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

查看更多
登录 后发表回答