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

此生再无相见时 提交于 2019-12-21 17:04:00

问题


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?

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!