Sie müssen Ihre filters ändern wie unten gezeigt.
Erklärung
- Wir fügen Filter in die Dokumentstruktur mit den
$addFieldsein Operator. Dies hilft uns, alle notwendigen Werte zu berechnen. - Wir filtern
toysmit den kürzlich enthaltenenfiltersAttribut mit dem$exprBetreiber. - Anwenden des
$filterOperator erhalten wir alle Spielzeuge mit dem gleichencodevonfilters. Jetzt können wirtotalberechnen undprice_totalWerte. - Wir könnten
total_coincidencesberechnen innerhalb der$groupStufe wie folgt:
Aber Sie haben "distinct element" erwähnt. Also erstellen wir einen Satz einzigartiger Spielzeugcodes und zählen die Artikel im Satz.
db.collection.aggregate([
{
$unwind: "$toys"
},
{
$addFields: {
"filters": [
{
"code": 17001,
"quantify": 2
},
{
"code": 17003,
"quantify": 4
},
{
"code": 17005,
"quantify": 5
},
{
"code": 17005,
"quantify": 6
}
]
}
},
{
$match: {
$expr: {
$in: [ "$toys.code", "$filters.code"]
}
}
},
{
$group: {
_id: "$toystore_name",
total_coincidences: {
$addToSet: "$toys.code"
},
toy_array: {
$push: {
"price_original": "$toys.price",
"toy": "$toys.toy",
"total": {
$size: {
$filter: {
input: "$filters",
cond: {
$eq: [ "$$this.code", "$toys.code"]
}
}
}
},
price_total: {
$sum: {
$map: {
input: {
$filter: {
input: "$filters",
cond: {
$eq: [ "$$this.code", "$toys.code" ]
}
}
},
in: {
$multiply: [ "$toys.price", "$$this.quantify" ]
}
}
}
}
}
}
}
},
{
$addFields: {
total_coincidences: {
$size: "$total_coincidences"
}
}
},
{
$sort: { _id: 1 }
}
])