如何检索Mongodb集合中的所有对象(包括ID)? [英] How to retrieve all objects in a Mongodb collection including the ids?
问题描述
我正在使用 Casbah 和 Salat 创建我自己的Mongodb dao,并实现了这样的getAll方法:
val dao: SalatDAO[T, ObjectId]
def getAll(): List[T] = dao.find(ref = MongoDBObject()).toList
我想知道的是:
- 是否有更好的方法来检索所有对象?
- 遍历对象时,找不到对象的_id.被排除在外吗?如何将其包括在列表中?
1°/ModelCompanion
特性提供了def findAll(): SalatMongoCursor[ObjectType] = dao.find(MongoDBObject.empty)
方法.您将必须对数据库中的每个集合进行专门的请求.
如果对返回的对象进行迭代,则最好使用dao.find
返回的SalatMongoCursor[T]
进行迭代,而不是进行两次迭代(一个迭代来自Iterator
特性的toList
,另一个迭代于List[T]
).
2°/Salat将_id键映射到您的班级ID字段.如果使用id: ObjectId
字段定义一个类.该字段与mongo _id键映射.
您可以使用 Salat文档 >
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°/ 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
这篇关于如何检索Mongodb集合中的所有对象(包括ID)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!