Saya memiliki koleksi MongoDB yang terlihat seperti ini:

{ "_id" : 1, "owner" : "Alice", airline: "RSAirlines", "content" : ["shoes", "pants", "sockets"]}
{ "_id" : 2, "owner" : "Bob", airline: "RSAirlines", "content" : ["phone", "pants"]}
{ "_id" : 3, "owner" : "Charlie", airline: "RSAirlines", "content" : ["shoes", "pants", "bag"]}
{ "_id" : 4, "owner" : "Mary" ,airline: "AirES" "content" : ["sandals", "coins", "sockets"]}
{ "_id" : 5, "owner" : "Olivia", airline: "AirES", "content" : ["gloves", "pants", "sockets"]}
{ "_id" : 6, "owner" : "Dan", airline: "AirES", "content" : ["sockets", "wallet"]}
{ "_id" : 7, "owner" : "Erin", airline: "AirES", "content" : ["pants", "sockets", "dress"]}

Saya ingin aggregate mereka mendapatkan hasil berikut:

{ "_id": "RSAirlines", "counts": {
    "shoes": 2,
    "pants": 3,
    "sockets": 1,
    "phone": 1,
    "bag": 1
}}
{ "_id": "AirES", "counts": {
    "sandals": 1,
    "coins": 1,
    "sockets": 4,
    "wallet": 1,
    "dress": 1,
   "pants": 2
}}

Sebelumnya saya melihat jawaban ini untuk menghitung elemen, tetapi sekarang saya akan suka menghitungnya dengan airline.

1
Kazh 27 Mei 2021, 18:14

1 menjawab

Jawaban Terbaik
  • $unwind mendekonstruksi array content
  • $group sebanyak airline dan content dan dapatkan jumlah totalnya
  • $group hanya dengan airline dan menyusun counts format nilai kunci larik
  • $arrayToObject mengonversi larik nilai kunci menjadi objek
db.collection.aggregate([
  { $unwind: "$content" },
  {
    $group: {
      _id: {
        airline: "$airline",
        content: "$content"
      },
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: "$_id.airline",
      counts: {
        $push: {
          k: "$_id.content",
          v: "$count"
        }
      }
    }
  },
  { $project: { counts: { $arrayToObject: "$counts" } } }
])

Tempat bermain

1
turivishal 27 Mei 2021, 15:27