嗨,我在使用 Jongo 使用$unwind
操作员从我的人员集合中获取地址列表时遇到问题。
如您所见,我将 Person 类定义如下:
public class Person {
@Id
private long personId;
private String name;
private int age;
private List<Address> addresses;
//getters and setters
Address 类的定义如下:
public class Address {
private String houseNumber;
private String road;
private String town;
private String postalCode;
//gettes and setters
查询非常简单:
public List<Address> getAddressByPersonId(long id) {
List<Address> list = persons.aggregate("{$project:{addresses:1}}")
.and("{$match:{_id:#}}",id)
.and("{$unwind: '$addresses'}")
.as(Address.class);
return list;
}
我的收藏:
> db.persons.find()
{ "name" : "Bob", "age" : 34, "addresses" : [ { "houseNumber" : "12",
"road" : "High Street", "town" : "Small Town", "postalCode" : "BC2 3DE"
}, { "houseNumber" : "12", "road" : "High Street", "town" :
"Small Town", "postalCode" : "BC2 3DE" } ], "_id" : NumberLong(1) }
>
我也对此进行了 JUnit 测试:
@Before
public void setUp(){
service = new PersonServiceImpl();
//store a person into the database (manually) before the tests
MongoCollection persons = Database.getInstance().getCollection(CollectionNames.PERSONS);
//create a new person
Person p = new Person();
p.setPersonId(1L);
p.setName("Bob");
p.setAge(34);
//create two addresses for this person
Address a = new Address();
a.setHouseNumber("33");
a.setRoad("Fake Road");
a.setPostalCode("AB1 2CD");
a.setTown("Big Town");
p.addAddress(a);
a.setHouseNumber("12");
a.setRoad("High Street");
a.setPostalCode("BC2 3DE");
a.setTown("Small Town");
p.addAddress(a);
persons.save(p);
}
@After
public void tearDown(){
service = null;
}
@Test
public void getAddressesByPersonIdTest(){
List<Address> list = service.getAddressByPersonId(1L);
for (Address item : list){
item.print();
}
Assert.assertTrue(list.size() > 0);
}
}
哪个输出
### Address: null null, null, null
### Address: null null, null, null
我不太明白问题是什么。显然测试没有失败(所以list.size()
大于零......但打印为空)。该print()
方法经过测试并且有效。
我想得到两个 Bob 的地址,但是查询返回空对象。我错过了什么吗?我应该以不同的方式使用$unwind吗?请建议