如何检索MongoDB中存储的子字段

时间:2014-09-25 05:56:17

标签: java mongodb spring-data spring-data-mongodb

以下数据存储在MongoDB中。我正在使用Spring-Data并将数据存储到mongoDB中。 如果我想检索字段(" id"或" Name")我可以做,但如果我想检索子字段(" firstName"或" lastName")我不能。

(例如)如果我想检索子字段" lastName"从以下数据我不能。在这方面任何人都可以帮助我。 提前谢谢。

MongoDB中存储的数据:

{

"id":101,

"name": {"firstName":"Mark",

         "lastName":"Antony"

         }
}

我使用的代码是:

PersonService.java

public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME); 
}

PersonController.java

@RequestMapping(value = "/person/search", method = RequestMethod.GET)  
public String search(@ModelAttribute Audit audit, ModelMap model) {  
model.addAttribute("personList", personService.searchPerson(audit)); 
return "output";
}  

Audit.java

@Document
public class Audit {
@Id
private String id;
private List<NameDetails> name;

public String getId() {
    System.out.println("Person: getId");
    return id;
}
public void setId(String id) {
    System.out.println("Person: setId");
    this.id = id;
}
public List<NameDetails> getName() {
    System.out.println("Audit: getName");
    return name;
}
public void setName(List<NameDetails> name) {
    System.out.println("Audit: setName");
    this.name = name;
}       

}

NameDetails.java

package com.register.mongo.model;

public class NameDetails {
private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}   
}

(output.jsp)UI页面

<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td> 
</tr>
<tr>
<td>${person.lastName}</td> 
</tr>
</c:forEach>
</table>    

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,你应该多做一个课程并在审核课程中使用它

public class NameDetails{

private String FirstName;
private String LastName;

public String getFirstName() {
return id;
}

public void seFirstName(String fisrtName) {

    this.FirstName= fisrtName;
}   
public String getLastName() {
    return LastName;
}
public void setLastName(String LastName) {
    this.LastName = LastName;
}
}

并在Audit.class中使用此类

@Document
public class Audit {
@Id
private String id;
private List name<NameDetails>;

然后是制定者和吸气剂