Reputation: 151
Here i have Two arrays,
Usercar = [{
parentId :001
cars:[
{_id: 1, name: bmw, color: red},
{_id: 2, name: Ford, color: black},
{_id: 3, name: Volkswagen, color: black},
]
}]
Userfavorite =
[{
parentId :001,
favoriteCars:[1,3] //mongoose.Types.ObjectId
}]
I want o show user favorite cars using mongodb aggregate, here is my code
let carsId= [1,3];
{$match: {
parentId :001
}},
{
$project:{
cars:{
$filter:{
input:"$cars",
as :'cars',
cond:{ $eq :["$$cars._id", mongoose.Types.ObjectId('1')]}
//cond:{ $eq :["$$cars._id", carsId]}
}
}
}
}
the above code only work, when pass single carsId, I want user favorite Cars details from Usercar's collection, how to do that in mongodb aggregate ?
Upvotes: 0
Views: 1071
Reputation: 28326
One possible aggregate that could do this is:
db.Usercar.aggregate([
{$lookup: {
from: "Userfavorite",
localField: "parentId",
foreignField: "parentId",
as: "favorite"
}},
{$set: {
favorite: {
$arrayElemAt: [
{$concatArrays: "$favorite.favoriteCars"},
0
]
}
}},
{$addFields: {
favoriteCarDetails: {
$filter: {
input: "$cars",
cond: {
$in: [
"$$this._id",
"$favorite"
]
}
}
}
}}
])
Upvotes: 1