Hi
My database structure is like this:
{
rootField: "value",
anotherRootField: "value1",
products:[
{
productName: "p1_name",
currencies: [
{
currencyName: "p1c1_name"
},
{
currencyName: "p1c2_name"
}
]
},
{
productName: "p2_name",
currencies: [
{
currencyName: "p2c1_name"
},
{
currencyName: "p2c2_name"
},
]
},
],
ships: [
{
shipDate: "shipDate"
},
...
]
}
For some reason users can send different queries which means I don’t know what exactly they want and also they can search for each level of my document.
My goal is to process the query and return the result as a microsoft excel file. for that I need to remove products/currencies/ships if they don’t match the query. for example for this query:
{
productName: "p1_name",
}
I need something like this:
{
rootField: "value",
anotherRootField: "value1",
products:[
{
productName: "p1_name",
currencies: [
{
currencyName: "p1c1_name"
},
{
currencyName: "p1c2_name"
}
]
}
]
}
or if search for currency:
{
currencyName: "p2c1_name",
}
I need this:
{
rootField: "value",
anotherRootField: "value1",
products:[
{
productName: "p2_name",
currencies: [
{
currencyName: "p2c1_name"
},
]
},
]
}
I have a hard time to understanding the aggregation framework and this is what I working on:
await Proforma.aggregate([
{ $match: { rootField: "value" } },// sample query
{ $unwind: "$products" },
{ $match: { "products.productName": "p1_name" } }, // sample query
{ $unwind: "$products.currencies" },
{ $match: { "products.currencies.currencyName": "p1c1_name"}}, // sample query
{ // back to array
$group: {
_id: { _id: "$_id", product__id: "$products._id" },
currencies: { $push: "$products.currencies" },
},
},
{ // back to array
$group: {
_id: "$_id._id",
products: {
$push: {
_id: "$id.product__id",
currencies: "$currencies",
},
},
},
},
]);
As I said my query could be very complex and contains multiple fields from root, products, currencies and ships so I don’t know is this works for my situations or not but my current problem is my rootFields get ignored from the result. I just want to filter nested fields and have rootFields untouched.
and also I don’t know how to add ships to this query
also filter does not work for me because sometimes my conditions contain a lot of nested $or and $and and i get this error:
MongoDB aggregate error: expression must have exactly one field