I am using Aggregation.lookup from Spring Data MongoDB to query data from 2 collections, and they are One-To-Many. Data structure and Java code are as followings:
Collection persons:
{ "name": "dave", "pets": [ 111, 112, 113] },
{ "name": "smith", "pets": [ 111, 112 ] },
{ "name": "ahn", "pets": [ 111, 112, 113 ] }
Collection pets
{"petId": 111, "petName": "dog", "petFood": "Meat"},
{"petId": 112, "petName": "rabbit", "petFood": "carrot"},
{"petId": 114, "petName": "cat", "petFood": "Fish"},
{"petId": 115, "petName": "fish", "petFood": "worm"}
Java Models:
@Document("persons")
public class Person {
@Id
String id;
String name;
@DocumentReference(lazy = false)
List<Pet> pets;
}
@Document("pets")
public class Pet {
@Id
String id;
String name;
@DocumentReference(lookup = "{ 'petId' : ?#{#target} }")
Person person;
}
AggregationOperation match = Aggregation.match(Criteria.where("name").is("smith"));
AggregationOperation query = Aggregation.lookup("pets", "pets", "petId", "pets");
Aggregation aggregation = Aggregation.newAggregation(query, match);
AggregationResults<Person> results = mongoTemplate.aggregate(aggregation,
mongoTemplate.getCollectionName(Person.class), Person.class);
return results.getMappedResults();
I printed out the executed MongoDB query in the console:
db.persons.aggregate([
{
"$lookup": {
"from": "pets",
"localField": "pets",
"foreignField": "petId",
"as": "pets"
}
},
{ "$match": { "name": "smith" } }
])
I run the query in mongo command line, and the result looks good that it includes pets details list:
[
{
_id: ObjectId("61f304711b35ae9b874cf800"),
name: 'smith',
pets: [
{
_id: ObjectId("61f2fe371b35ae9b874cf7f4"),
petId: 111,
petName: 'dog',
petFood: 'Meat'
},
{
_id: ObjectId("61f2fe371b35ae9b874cf7f5"),
petId: 112,
petName: 'rabbit',
petFood: 'carrot'
}
]
}
]
The problem is, the results from Java code only contains Person data, and the list of pets is empty. Did I miss something in the Java code?
It would be appreciated if someone could help me with this.