Cara menggunakan mongodb group by sum

Kamran Ahmed: [0:00] Here in our tweets collection we have a separate document for each of the tweets from a specific user. If we look at the first tweet, it says from screen_name jsbot, if we look at the second tweet it is again from jsbot, if we look at the third tweet, it's from user.screen_name FCBarcelona.

[0:15] Let's say that we want to count the number of tweets from each of the users in this collection. For that we can use the aggregate. I will do db.tweets.aggregate.

[0:23] Our first line is going to be $group. $group is an object, with the first field as _id, which is the column on which you want to group.

[0:30] In our case we want to group on the user.screen_name, so I will do $user.screen_name, and the rest of the parameters of the project We want to count, so I will have another field called count, and we will make it using the sum of 1.

[0:44] If I run this query you will see that we are getting that documents, and in each of the document we have the user_name as id, which is this one, and in the count we are getting the number of tweets from this user. Our sum in this case is doing is whenever is finding the user.screen_name and keeps preparing a group, if it already has a group for that, it just keeps adding one into that. In this case, for LFC, whenever it finds a new user.ScreenName with LFC, it keeps adding one into the current field.

[1:08] For sum we can also give it any field of the document that we have. If you look at the tweets collection, we have a Favorite Count Field in each of the documents.

[1:15] Let's say that we want to get the sum of "Likes" that each of the account has got on their tweets. What I'm going to do now is I'm going to replace count with the Tweet Count, and I'm going to add another field called Favorite Count, which is going to be sum of the Field Favorite Count.

[1:28] If I run the [inaudible] , you will see that in each of the documents we are getting the Tweet Count and the Favorite Count. The Firefox now has one tweet, and Total Favorites that they have got is 14. If you look at Yahoo, they have 11 tweets and Total Favorite Count that they have is 21.

[1:41] Let's start over with users by the people who tweet the most. For that, I'm going to add another stage called Sort. We are going to sort by tweet count in the descending order.

[1:49] If I run the [inaudible] , you will see that GsBot has the most tweets, 226. The second one is 51, and the third one is 50.

[1:56] If you want to get the list of all the users who tweet less than anyone else, we can do +1, so this will be ascending order now. This one has one tweet. The second one has one tweet again, and so on.

MongoDB terpolimerisasi (agregat) terutama untuk pengolahan data (seperti rata-rata statistik, jumlah, dll), dan mengembalikan hasil data dihitung. count pernyataan sql agak mirip (*).


() Metode agregat

Metode polimerisasi MongoDB menggunakan agregat ().

tatabahasa

Dasar sintaks agregat () metode adalah sebagai berikut:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

contoh

pengumpulan data adalah sebagai berikut:

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'w3cschool.cc',
   url: 'http://www.w3cschool.cc',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'w3cschool.cc',
   url: 'http://www.w3cschool.cc',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
},

Sekarang kita atur di atas dihitung untuk setiap jumlah artikel yang ditulis oleh penulis menggunakan agregat () dihitung sebagai berikut:

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "w3cschool.cc",
         "num_tutorial" : 2
      },
      {
         "_id" : "Neo4j",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}
>

Contoh yang sama atas pernyataan sql: pilih by_user, count (*) dari grup mycol oleh by_user

Dalam contoh di atas, kita by_user lapangan dengan lapangan untuk kelompok data dan menghitung jumlah dari nilai yang sama by_user lapangan.

Tabel berikut menunjukkan beberapa ekspresi agregasi:

ekspresideskripsicontoh$ SumMenghitung jumlahnya.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", num_tutorial: {$ sum: "$ suka"}}}])$ rataMenghitung rata-ratadb.mycol.aggregate ([{$ grup: {_id: "$ by_user", num_tutorial: {$ avg: "$ suka"}}}])$ MinMendapat koleksi semua dokumen sesuai minimum senilai.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", num_tutorial: {$ min: "$ suka"}}}])$ MaxMendapat koleksi semua dokumen yang sesuai dengan nilai maksimum.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", num_tutorial: {$ max: "$ suka"}}}])$ DorongDalam dokumen yang dihasilkan untuk memasukkan nilai ke dalam array.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", url: {$ push: "$ url"}}}])$ AddToSetDalam dokumen yang dihasilkan untuk memasukkan nilai ke array, tetapi tidak membuat copy.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", url: {$ addToSet: "$ url"}}}])$ PertamaMenjadi data dokumen pertama sesuai dengan dokumen sumber daya semacam.db.mycol.aggregate ([{$ grup: {_id: "$ by_user", first_url: {$ pertama: "$ url"}}}])$ terakhirMendapatkan data dokumen terakhir sesuai dengan dokumen sumber daya semacamdb.mycol.aggregate ([{$ grup: {_id: "$ by_user", last_url: {$ terakhir: "$ url"}}}])

Konsep pipeline

Pipa di Unix dan Linux pada umumnya digunakan untuk keluaran perintah saat ini sebagai parameter untuk perintah selanjutnya.

MongoDB MongoDB dokumen polimer pipa di pipa setelah hasil diproses untuk pengolahan pipa berikutnya. operasi pipa dapat diulang.

Ekspresi: pengolahan input dan output dokumen. Ekspresi stateless, hanya dapat digunakan untuk menghitung pipa saat dokumen agregat, Anda tidak bisa berurusan dengan dokumen lainnya.

Di sini kami memperkenalkan kerangka agregasi umum digunakan dalam beberapa operasi:

  • $ Project: Memodifikasi struktur dokumen masukan. Dapat digunakan untuk mengubah nama, menambah atau menghapus bidang, juga dapat digunakan untuk membuat perhitungan bersarang dan dokumentasi.
  • $ Pertandingan: digunakan untuk menyaring data, hanya output dari dokumen yang berkualitas. $ Pertandingan menggunakan MongoDB permintaan standar operator.
  • $ Limit: untuk membatasi jumlah dokumen pipa polimerisasi MongoDB kembali.
  • $ Lewati: Loncat jumlah tertentu dokumen dalam pipa polimerisasi, dan mengembalikan sisa dokumen.
  • $ Unwind: dokumen dibagi dalam berbagai bidang jenis menjadi beberapa, setiap array yang berisi nilai.
  • $ Kelompok: koleksi dokumen pengelompokan dapat digunakan untuk hasil statistik.
  • $ Urutan output dokumen masukan setelah pemesanan.
  • $ GeoNear: Memerintahkan output dokumen dekat dengan lokasi geografis.

Contoh operator pipa

1, contoh proyek $

db.article.aggregate(
    { $project : {
        title : 1 ,
        author : 1 ,
    }}
 );

Dalam hal ini hasil hanya akan ada _id, tilte dan penulis tiga bidang, bidang standar _id adalah untuk dimasukkan, jika order tidak berisi _id jika dapat:

db.article.aggregate(
    { $project : {
        _id : 0 ,
        title : 1 ,
        author : 1
    }});

2. contoh pertandingan $

db.articles.aggregate( [
                        { $match : { score : { $gt : 70, $lte : 90 } } },
                        { $group: { _id: null, count: { $sum: 1 } } }
                       ] );

$ Pertandingan digunakan untuk memperoleh skor lebih besar dari 70 adalah kurang dari atau sama dengan 90 catatan, maka catatan yang cocok untuk tahap berikutnya dari operator pipa $ kelompok untuk diproses.