Estoy obteniendo una lista de registros que tienen alguna referencia anidada a otra colección, quiero completar ese ObjectId anidado que está dentro de una matriz de objetos, con una consulta de búsqueda agregada de mongoDb.
Así es como es la estructura de la colección DB:
{ subject: {type: String}, body: {type: String}, recipients: [{ userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, stutus: {type: String, enum: ['pending','accepted','rejected'], default:'pending'} }], sender: {type: mongoose.Schema.Types.ObjectId, ref: 'User'} }Lo que estoy esperando:
[{ subject: 'Some subject here.', body: 'Lorem ipsum dolor emit set', recipients: [{ userId: {firstName: 'John', lastName: 'Doe'}, status: 'accepted' },{ userId: {firstName: 'Jane', lastName: 'Doe'}, status: 'accepted' }], sender: {firstName: 'Jacobs', 'lastName': 'Doe'} },{ subject: 'Some subject here.', body: 'Lorem ipsum dolor emit set', recipients: [{ userId: {firstName: 'Jane', lastName: 'Doe'}, status: 'rejected' },{ userId: {firstName: 'John', lastName: 'Doe'}, status: 'accepted' }], sender: {firstName: 'Jacobs', 'lastName': 'Doe'} }]Cualquier tipo de ayuda será muy apreciada.
$unwind deconstruye matriz de recipients$lookup con la colección de usuarios para recipients.userId$unwind deconstruir recipients.userId de ID de usuario$lookup con la colección de usuarios para el sender$unwind deconstruir matriz de sender$group por _id y reconstruir la matriz de recipients db.mails.aggregate([ { $unwind: "$recipients" }, { $lookup: { from: "users", localField: "recipients.userId", foreignField: "_id", as: "recipients.userId" } }, { $unwind: "$recipients.userId" }, { $lookup: { from: "users", localField: "sender", foreignField: "_id", as: "sender" } }, { $unwind: "$sender" }, { $group: { _id: "$_id", recipients: { $push: "$recipients" }, subject: { $first: "$subject" }, body: { $first: "$body" }, sender: { $first: "$sender" } } } ])Prueba esto:
db.emails.aggregate([ { $unwind: "$recipients" }, { $lookup: { from: "users", let: { userId: "$recipients.userId", status: "$recipients.stutus" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$userId"] } } }, { $project: { "_id": 0, "userId": { "firstName": "$firstName", "lastName": "$lastName", }, "status": "$$status" } } ], as: "recipient" } }, { $lookup: { from: "users", let: { userId: "$sender" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$userId"] } } }, { $project: { "_id": 0, "firstName": 1, "lastName": 1 } } ], as: "sender" } }, { $group: { _id: "$_id", subject: { $first: "$subject" }, body: { $first: "$body" }, recipients: { $push: { $arrayElemAt: ["$recipient", 0] } }, sender: { $first: { $arrayElemAt: ["$sender", 0] } } } } ]);