2016-07-11 3 views
1

kombiniert Ich habe folgende Datensatz:

{ 
    "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"), 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]", 
    "goals" : [ 
    { 
     "gId" : "base1", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 
    }, 
    { 
     "gId" : "base2", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 

    }, 
    { 
     "gId" : "base1", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 

    } 
] 
} 

ich folgendes Ergebnis benötigen:

{ 
    "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"), 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]", 
    "goals" : [ 
    { 
     "gId" : "base1", 
     "count" : 2 
    }, 
    { 
     "gId" : "base2", 
     "count" : 1 
    } 
    ] 
} 

Bisher spielte ich um mit dem Aggregat Abfrage aber ich konnte keine Lösung für mein Problem finden. Meine Abfrage sieht so aus, aber es funktioniert nicht. Das erste Bit $project läuft alleine gut und so tut $unwind und $group aber ich weiß nicht, wie ich es zusammen kombinieren kann.

db.getCollection('users').aggregate(
{ 
    $project : { 
    firstname: "$firstname", 
    surname: "$surname", 
    email: "$email", 
    goals: "$goals" 
    } 
}, 
{ 
    $unwind: '$goals' 
}, 
{ 
    $group: { 
    gid: '$goals.gId', 
    count: {'$sum': 1} 
    } 
} 
) 

Vielen Dank im Voraus, Tom

Antwort

1

Versuchen Sie es mit der folgenden Pipeline wie dieses WOW

{ 
    "goals" : [ 
     { 
      "gId" : "base2", 
      "count" : 1.0 
     }, 
     { 
      "gId" : "base1", 
      "count" : 2.0 
     } 
    ], 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]" 
} 
+0

sieht

db.getCollection('users').aggregate( { $unwind: '$goals' }, { $group: { _id: { firstname: "$firstname", surname: "$surname", email: "$email", gId: "$goals.gId" }, count: {'$sum': 1} } }, { $group: { _id: { firstname: "$_id.firstname", surname: "$_id.surname", email: "$_id.email" }, goals: { $push: { gId: "$_id.gId", count: "$count" } } } }, { $project: { _id: 0, firstname: "$_id.firstname", surname: "$_id.surname", email: "$_id.email", goals: 1 } } ) 

Ergebnis. Wie bist du auf eine solche Frage gekommen? Es ist ziemlich nah dran: "Ziele": [ { "count": 2,0 }, { "count": 1,0 } ], "Vorname": "First1", "Nachname": „Sur1 ", " email ":" [email protected] " } aber ich brauche die Beschreibung des Ziels auch wie { " count ": 1.0, gid:" base2 "} –

+0

Die" base2 "," base1 " ist tatsächlich in den Elementen des Arrays enthalten. Bitte überprüfe es nocheinmal – DAXaholic