mongodb - Morphia/MongoDB : Accessing "embedding" object from an @Embedded object

标签 mongodb morphia

我有一个与此类似的 Morphia 架构:

@Entity
class BlogEntry {
    @Embedded
    List<BlogComment> comments
}

@Embedded
class BlogComment {
    String content
    Long authorId
}

(上面的代码仅供说明)

我正在尝试获取特定的 BlogComment,以便用新内容更新它。我有相应的 BlogEntry 对象可用,并且有authorId,就本问题而言,这两个对象足以唯一地标识正确的 BlogComment。

我的问题是,BlogComment 没有显式包含对其“父”BlogEntry 对象的引用,那么我如何编写一个 morphia 查询来检索此 BlogComment?像这样的东西:

//fetch the unique comment corresponding to this blog entry and this author ID.
BlogComment comment = ds.find(BlogComment.class, "blogEntryId =", blogEntry.id)
                        .filter("authorId", authorId)
                        .get(); 

最佳答案

既然您已经有了博客条目对象,为什么不使用简单的 Java 循环来过滤它呢?

@Entity
class BlogEntry {

    @Embedded
    List<BlogComment> comments

    public BlogComment findCommentByAuthorId(String authorId) {
        if (null == authorId) return null;
        for (BlogComment comment: blogEntry.comments) {
           if (authorId.equals(comment.authorId) return comment;
        }
        return null;
    }

}

关于mongodb - Morphia/MongoDB : Accessing "embedding" object from an @Embedded object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884813/

相关文章:

mongodb - 检索 MongoDB/Morphia 中的数组数组?

java - createDatastore 是否具有破坏性?

java - Morphia 中用于嵌套类的 ORM

node.js - NestJS - 每个模块使用多个 MongoDB 连接

angularjs - 在更新/删除文档之前,如何检查 Passport JS 中的 req.user 中的 userID 和 MongdoDB userID 是否匹配?

javascript - 如何在 JavaScript 中将 Decimal128 值转换为数字?

java - Morphia 数据存储获取、保存、删除查询

mongodb - 在 Sitecore 8 中重建报告数据库

c# - MongoDB C# 2.1 ReplaceOneAsync 不适用于存储库模式

java - 通过比较字段进行吗啡查询