如何检索Mongodb集合中的所有对象(包括ID)? [英] How to retrieve all objects in a Mongodb collection including the ids?

查看:499
本文介绍了如何检索Mongodb集合中的所有对象(包括ID)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Casbah Salat 创建我自己的Mongodb dao,并实现了这样的getAll方法:

val dao: SalatDAO[T, ObjectId]    
def getAll(): List[T] = dao.find(ref = MongoDBObject()).toList 

我想知道的是:

  1. 是否有更好的方法来检索所有对象?
  2. 遍历对象时,找不到对象的_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:

  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°/ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆