简体   繁体   English

Spring mongodb @DBRef 查询以在基本查询中搜索父字段

[英]Spring mongodb @DBRef query to search parent field in Basic Query

How can query mongodb to search all publications where author first name is "Vinod"?如何查询 mongodb 以搜索所有作者名字为“Vinod”的出版物?

Here is my Publication Class这是我的出版课

@Document(collection = "publications")
public class Publication {

    @Id
    private String id;

    private String title;

    private Date publicationDate;

    @DBRef
    private Author author;

    //getter and setters here
}

And my author class is我的作者班是

@Document(collection = "authors")
public class Author {

    @Id
    private String id;

    @Indexed(unique = true)
    private String username;

    private String firstName;

    private String lastName;

    //getter and setters here
}

This is how it is stored in the database.这就是它在数据库中的存储方式。

Publication出版物

{
  "_id" : ObjectId("5a339cc4e193d31c47916c2c"),
   "_class" : "com.publication.models.Publication",
  "title" : "Some title",
  "publicationDate" : ISODate("2017-12-15T09:58:28.617Z"),
  "author" : {
    "$ref" : "authors",
    "$id" : ObjectId("5a339cc0e193d31c47916ad0")
  }
}

And author:和作者:

{
  "_id" : ObjectId("5a339cc0e193d31c47916ad0"),
  "_class" : "com.publication.models.Author",
  "username" : "abcd0050",
  "firstName" : "Vinod",
  "lastName" : "Kumar"
}

This is how I need to query.这就是我需要查询的方式。

BasicQuery query = new BasicQuery("{ author.name : 'vinod' }");
Publication test = mongoOperation.find(query, Publication.class);

This should work这应该工作

Query query = Query.query(new Criteria("author.name", "vinod"));
Publication test = mongoOperation.find(query, Publication.class);

You could also do你也可以这样做

BasicQuery basicQuery = new BasicQuery().addCriteria(new Criteria("author.name", "vinod"))

我建议您使用 RelMongo,它是一个构建在 Spring Data 之上的小框架,允许以 JPA 方式将 @OneToMany 和 @OneToOne 注释与 MongoDB 集合一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM