如何检索Mongodb集合中的所有对象(包括ID)?

编程入门 行业动态 更新时间:2024-10-28 20:16:46
本文介绍了如何检索Mongodb集合中的所有对象(包括ID)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 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)?

    本文发布于:2023-08-01 05:22:33,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1265562.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   Mongodb   ID

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!