MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Wie finde ich ein Array von Werten in einer $match-Aggregation und gruppiere das Ergebnis?

Du musst deine filters wie unten gezeigt anpassen.

Erläuterung

  1. Wir fügen die Filter mit dem Operator $addFields in die Dokumentstruktur ein. So können wir alle benötigten Werte berechnen.
  2. Wir filtern toys mit dem soeben hinzugefügten Attribut filters über den Operator $expr.
  3. Mit dem Operator $filter erhalten wir alle Toys mit demselben code aus filters. Nun können wir die Werte total und price_total berechnen.
  4. Den Wert total_coincidences könnten wir innerhalb der $group-Stufe so berechnen:

Da du aber „eindeutige Elemente“ erwähnt hast, erzeugen wir eine Menge eindeutiger Toy-Codes und zählen die Elemente in der Menge.

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 } }
])

Mongo Playground