如何查询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);
我建议您为您提供relmongo,这是一个在弹簧数据顶部构建的小框架,以允许使用@Onetomany和@OnetoOne注释,以JPA方式使用MongoDB收集
这应该有效
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"))