Hi I am having problems using Jongo to get a list of Addresses from my collection of Persons using the $unwind
operator.
As you can see I defined the Person class as follows:
public class Person {
@Id
private long personId;
private String name;
private int age;
private List<Address> addresses;
//getters and setters
and the Address class is defined like:
public class Address {
private String houseNumber;
private String road;
private String town;
private String postalCode;
//gettes and setters
The Query is pretty simple:
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;
}
My collection:
> 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) }
>
I have a JUnit test for this as well:
@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);
}
}
Which outputs
### Address: null null, null, null
### Address: null null, null, null
I don't understand very well what the problem is. Apparently the test does not fail (so list.size()
is bigger than zero...but prints null). The print()
method is tested and works.
I would like to get the two Bob's addresses , however the query returns null objects. Am I missing something? Should I use the $unwind differently? Please suggest