I'm working on a MongoDB database created by me for educational purposes. This document is formed by 2 collections: characters and objects. Here is an example.
/* CHARACTERS */
{
"_id":"character_name1",
/*other no-relevant informations*/
"inventory" : [
{ "name":"object_name1"},
{ "name":"object_name2"}
]
},
{
"_id":"character_name2",
/*other no-relevant informations*/
"inventory" : [
{ "name":"object_name2"},
{ "name":"object_name3"}
]
}
/* OBJECT */
{
"name":"object_name1",
/*other no-important informations*/
"effects" : [
{"health":10},
{"mana":200}
]
},
{
"name":"object_name2",
/*other no-important informations*/
"effects" : [
{"charisma":10},
{"strenght":200}
]
}
Now, I'm trying to display the ids of character that own objects that have the key "charisma" in "effects" array. The result of the following piece of code is correct but it prints the ID of the owner for every object that respects the $match statement.
db.character.aggregate([
{
$lookup: {
"localField": "inventory.name",
"from": "objects",
"foreignField": "name",
"as": "object_list"
}
},
{
$unwind : "$object_list",
},
{
$match : {
"object_list.effects.charisma": {$exists:true}
}
},
{
$project:{
"_id":"$_id",
"object_name":"$lista_oggetti.nome"
}
}
]
).pretty()
If I use $group instead of $project the program starts an "infinite" computation. Any suggestion?