2016-04-16 14 views
0

Ich habe Dokumente wie unten.Embedded Dokument in Mongodb entpacken

{ 
    "_id": { 
     "$oid": "526fdc1fd6b0a8182300009c" 
      }, 
    "body": "test abc", 
    "emb" : [{"body":"text","em":"abc.com","auth":"XYZ"}, 
      {"body":"text","em":"abc.com","auth":"ABC"} 
      ] 
} 
{ 
    "_id": { 
     "$oid": "526fdc1fd6b0a8182300009d" 
      }, 
    "body": "test abc", 
    "emb" : [{"body":"text","em":"abc.com","auth":"PQR"}, 
      {"body":"text","em":"abc.com","auth":"ABC"} 
      ] 
} 

Wenn ich will, die Dokumente in der inneren Anordnung Vorkommen jeder „Auth“ zählen, wie kann ich das tun? Das Ergebnis ich erwarte ist

"ABC":2 
"PQR":1 
"XYZ":1 

Antwort

1
  1. $unwind die emb Array mit {$unwind: "$emb"}
  2. Gruppe von emb.auth während mit Zählen {$group: { _id: "$emb.auth", count: { $sum:1 } } }

Dies gibt Ihnen die Informationen, die Sie wollen, wenn auch in einer etwas anderen Syntax:

{ _id:"ABC", count:2 }, 
{ _id:"PQR", count:1 }, 
{ _id:"XYZ", count:1 } 
Verwandte Themen