Necesito tomar solo valores únicos de la colección. Por ejemplo:
const userID = `user1`; const users = await Chat .find({'$or': [{to: userID}, {from: userID}]}) .select(`-_id to from`) .lean(); // users will be like: [ {from: `user1`, to: `user2`}, {from: `user1`, to: `user2`}, {from: `user1`, to: `user2`}, {from: `user2`, to: `user1`}, {from: `user3`, to: `user1`}, // ... 10089 more items ]; // and I want this in result const result = [`user2`, `user3`]; // exclude current user too Sé que puedo hacer esto usando JS. Puedo crear una matriz de usuarios y ejecutar un new Set() , pero será lento. ¿Puede Mongoose hacer esto en mi lugar?
Puede probar la consulta de agregación,
$match su condición$group por nulo y construir una matriz única from usuario to usuario$setUnion para obtener users únicos from y to matriz$filter para iterar el bucle de la matriz de unión anterior y eliminar el usuario actual const userID = mongoose.Types.ObjectId(`user1`); const users = await Chat.aggregate([ { $match: { $or: [{ to: userID }, { from: userID }] } }, { $group: { _id: null, from: { $addToSet: "$from" }, to: { $addToSet: "$to" } } }, { $project: { _id: 0, users: { $filter: { input: { $setUnion: ["$from", "$to"] }, cond: { $ne: ["$$this", userID] } } } } } ]).exec(); console.log(users[0].users);