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

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


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


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.