从mongoDB中检索嵌入的文档

时间:2014-10-08 12:07:05

标签: java mongodb spring-mvc spring-data

以下数据存储在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页面

<form action="person/search" method="get">
<table>
<tr><td>
<label>Name</label>
<input type="text" id="lastName" name="lastName"/>
</td></tr>
<tr><td>
<input type="submit" value="Search"/>
</td></tr>
</table>
</form>    

<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)

更改

return mongoTemplate.find(
    new Query(Criteria.where("name.lastName").is(name.get(0))), 
    Audit.class,COLLECTION_NAME);

return mongoTemplate.find(
    new Query(Criteria.where("name.lastName").is(name.get(0).getLastName())), 
    Audit.class,COLLECTION_NAME);

您正在尝试使用整个NameDetails而不是姓氏。