students
{
"name" : "abc"
"class" : "1"
"subjects" : DBRef("subjects","class1")
}
和我的第二个系列
subjects
{
"_id" : "class1"
"sub1" : "english"
"sub2" : "physics"
}
我希望在加入上述两个集合之后实现我的输出
{
"name" : "abc"
"class" : "1"
"subjects" : {sub1 : "english",sub2 : "physics"}
}
有可能,如果是的话怎么样?
解决方法:
您可以使用@DBRef从Student引用Subjects文档.
The mapping framework doesn’t have to store child objects embedded
within the document. You can also store them separately and use a
DBRef to refer to that document. When the object is loaded from
MongoDB, those references will be eagerly resolved and you will get
back a mapped object that looks the same as if it had been stored
embedded within your master document.Here’s an example of using a DBRef to refer to a specific document
that exists independently of the object in which it is referenced
(both classes are shown in-line for brevity’s sake):
编辑:-
实际上,为了给你更多的细节,@ DBRef注释会急切地加载数据(在这种情况下是主题).
学生模特课: –
@Document(collection = "students")
public class Students implements Serializable, BaseDocument {
private static final long serialVersionUID = -3534650012619938612L;
@Id
private String id;
@Field("class")
private String className;
@DBRef
@Field("subjects")
private Subject subject;
public String getId() {
return id;
}
public String getClassName() {
return className;
}
public void setId(String id) {
this.id = id;
}
public void setClassName(String className) {
this.className = className;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Students [id=" + id + ", className=" + className + ", subject=" + subject + "]";
}
}
科目类型: –
@Document(collection = "subjects")
public class Subject implements Serializable, BaseDocument {
private static final long serialVersionUID = -3534650012619938612L;
@Id
private String id;
private String sub1;
private String sub2;
public String getId() {
return id;
}
public String getSub1() {
return sub1;
}
public String getSub2() {
return sub2;
}
public void setId(String id) {
this.id = id;
}
public void setSub1(String sub1) {
this.sub1 = sub1;
}
public void setSub2(String sub2) {
this.sub2 = sub2;
}
@Override
public String toString() {
return "Subject [id=" + id + ", sub1=" + sub1 + ", sub2=" + sub2 + "]";
}
}
按身份获取学生: –
当您通过Id获得学生时,框架/ mongodb将自动加载主题数据.您无需专门进行连接即可获取主题数据.
public Students getStudents(String id) {
MongoOperations mongoOperations = getMongoConnection();
Students students = mongoOperations.findById(id, Students.class);
System.out.println(students.toString());
return students;
}
输出: –
Students [id=584ea66e9e53b7802651de36, className=1, subject=Subject [id=class1, sub1=english, sub2=physics]]
科目集: –
{
"_id" : "class1",
"sub1" : "english",
"sub2" : "physics"
}
学生收藏: –
{
"_id" : ObjectId("584ea66e9e53b7802651de36"),
"name" : "abc",
"class" : "1",
"subjects" : {
"$ref" : "subjects",
"$id" : "class1",
"$db" : "localhost"
}
}