I'm using MongoDB(Atlas) in my project and I want to use aggregate. but I have a problem getting data.
I have two collections.
users:{
username:'test',
full_name:'test'
}
profiles:{
avatar:''
}
I use this code to search users by input query
const searchedUser = await User.aggregate([
{
$search: {
index: 'User',
text: {
query: `${query}`,
path: {
wildcard: '*',
},
fuzzy: {
maxEdits: 2,
},
},
},
},
{
$project: {
full_name: true,
username: true,
},
},
{
$lookup: {
from: 'profiles',
localField: 'user',
foreignField: 'id',
as: 'avatar',
},
},
]);
but I get all user avatars in the array for each user. I just wanna only that user avatar.
You need to add a projection with $arrayElemAt after your $lookup like this:
const searchedUser = await User.aggregate([{
$search: {
index: 'User',
text: {
query: `${query}`,
path: {
wildcard: '*',
},
fuzzy: {
maxEdits: 2,
},
},
},
},
{
$project: {
full_name: true,
username: true,
},
},
{
$lookup: {
from: 'profiles',
localField: 'user',
foreignField: 'id',
as: 'avatar',
},
},
{
$project: {
full_name: true,
username: true,
avatar: {
$arrayElemAt: ["$avatar", 0]
}
}
}
]);