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

时间:2017-12-15 10:03:10

标签: java spring mongodb spring-boot mongoose

如何查询mongodb搜索作者名字所在的所有出版物" Vinod"?

这是我的出版物

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

    @Id
    private String id;

    private String title;

    private Date publicationDate;

    @DBRef
    private Author author;

    //getter and setters here
}

我的作者班是

@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
}

这是它存储在数据库中的方式。

公开

{
  "_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")
  }
}

作者:

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

这是我需要查询的方式。

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

2 个答案:

答案 0 :(得分:1)

我建议你使用RelMongo这是一个基于Spring Data构建的小框架,允许在JPA方式中使用@OneToMany和@OneToOne注释与MongoDB集合

答案 1 :(得分:0)

这应该有效

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

您也可以

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