Hi there, as a new in MongoDB, I’m trying to get the specified data using aggregation but I’m getting an error even when I tried other ways still i got an empty array …
I only need the items obj that matches the productId
const item = await Cart.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: ["$$items.productId", productId] },
},
},
},
},
]);
Hi Diwash,
You are using $gte operator instead of $eq, also you are passing the wrong variable in the array. Here is the corrected pipeline stage -
{
$project:
{
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$eq: ["$$item.productId", productId],
},
},
},
}
}
1 Like
Thanks @Akshat_Gupta3
but now I’m getting an empty array and I only need the obj that matches the productId
[ { _id: new ObjectId('65eeafd35fa4289f83fee325'), items: [] } ]
Can you please share how you are passing the productId?
well I m extracting it from the body like this
const { user, item } = req.body;
const { productId } = item;
const product = await Cart.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$eq: ["$$item.productId", productId],
},
},
},
},
},
]);
Thanks @Akshat_Gupta3 bro
it was my mistake I was providing the id as a string
Thanks for the guidance
1 Like
system
(system)
Closed
March 16, 2024, 11:46am
7
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.