MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

MongoDB Mostrar itens filhos no relacionamento Um para Muitos


O pipeline a seguir deve lhe dar a ideia
db.getCollection('yourCollection').aggregate(
    {
        $unwind: {
            path: "$dates",
            includeArrayIndex: "idx"
        }
    },
    {
        $project: {
            _id: 0,
            dates: 1,
            numbers: { $arrayElemAt: ["$numbers", "$idx"] },
            goals: { $arrayElemAt: ["$goals", "$idx"] },
            durations: { $arrayElemAt: ["$durations", "$idx"] }
        }
    }
)

que produz a seguinte saída para sua amostra
/* 1 */
{
    "dates" : NumberLong(1399518702000),
    "numbers" : "5982",
    "goals" : "1",
    "durations" : "78"
}

/* 2 */
{
    "dates" : NumberLong(1399126333000),
    "numbers" : "5983",
    "goals" : "0",
    "durations" : "45"
}

/* 3 */
{
    "dates" : NumberLong(1399209192000),
    "numbers" : "5984",
    "goals" : "4",
    "durations" : "90"
}

/* 4 */
{
    "dates" : NumberLong(1399027545000),
    "numbers" : "5985",
    "goals" : "2",
    "durations" : "90"
}