MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

Jak grupować w agregacie, ale także wyświetlać inne pola za pomocą Mongo?

Nie opublikowałeś początkowej struktury dokumentu.

Document Structure:

{
    "_id" : ObjectId("50b59cd75bed76f46522c471"),
    "comment_id" : 61,
    "post_id" : 29,
    "comments" : [
                   {
                       "type" : "accepted",
                       "like" : 3
                   },
                   {
                      "type" : "rejected",
                      "like" : 3
                   },
                   {
                      "type" : "spam",
                      "like" : 3
                   }
                ]
}

Zakładając, że struktura twojego dokumentu jest jak powyżej, skomponowałem to zapytanie. Musisz nim manipulować zgodnie ze swoimi potrzebami.

db.posts.aggregate([
        {$unwind:"$comments"},
        {$match:{"$comments.type":{$ne:"spam"}}},
        {$group:{_id:{post_id:"$post_id",comment_id:"$comment_id"},LikeSum:{$sum:"$comments.like"}}},
        {$group:{_id:{post_id:"$_id.post_id"},AvgComments:{$avg:"$LikeSum"}}},
        {$sort:{AvgComments:-1}},
        {$limit:1}
              ])

Powyższe zapytanie jest skonstruowane w następujący sposób:

1.) Unwind the comments array and form individual documents for each element in the comments array
2.) Select only the non-spam comments
3.) Calculate the sum of likes for each comment of all posts
4.) Calculate the average Comment likes for each post
5.) Sort documents in descending order of Average Comment Likes
6.) Select only the first document.

Dokument wyjściowy będzie wyglądał jak

{
    "result" : [
        {
            "_id" : {
                       "post_id" : xx
                    },
            "AvgComments" : xx.xx // Avg Comment likes for post xx
        }
               ],
    "ok" : 1
}



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Nie można zaimportować MongoClient

  2. usługi warzenia piwa. Nie można uruchomić usługi. get Bootstrap nie powiodło się:5:Błąd wejścia/wyjścia

  3. prosty system głosowania z MongoDB

  4. Zapobiegaj podwójnemu logowaniu za pomocą FOSUserBundle

  5. Korzystanie z mongoDB w routerach Express