2016-09-12 4 views
1

Lasst uns sagen, dass ich die folgenden Dokumente in einer MongoDB Sammlung haben (dies ist nur eine vereinfachte Version meiner realen Daten):MongoDB Aggregation Abfrage mit Abwickler ohne preserveNullAndEmptyArrays

/* 1 */ 
{ 
    "_id" : "objectives/core/1001", 
    "tmp" : [ 
     { 
      "name" : "analysisType" 
     }, 
     { 
      "name" : "sampleFormat" 
     } 
    ] 
} 
/* 2 */ 
{ 
    "_id" : "objectives/core/1003", 
    "tmp" : [ 
     { 
      "name" : "analysisType" 
     } 
    ] 
} 
/* 3 */ 
{ 
    "_id" : "objectives/core/1004", 
    "tmp" : [] 
} 

Beachten Sie, dass das letzte Dokument hat leer tmp Array.

ich eine Aggregations Abfrage mit Mongo 3.2, die tmp "abwickelt" schrieb und bewahrt leere Arrays:

db.entities.aggregate({ "$unwind" : { path: "$tmp", preserveNullAndEmptyArrays: true } }); 

Und hier ist meine (gewünschte) Ausgabe:

/* 1 */ 
{ 
    "_id" : "objectives/core/1001", 
    "tmp" : { "name" : "analysisType" } 
} 
/* 2 */ 
{ 
    "_id" : "objectives/core/1001", 
    "tmp" : { 
     "name" : "sampleFormat" 
    } 
} 
/* 3 */ 
{ 
    "_id" : "objectives/core/1003", 
    "tmp" : { "name" : "analysisType" } 
} 
/* 4 */ 
{ "_id" : "objectives/core/1004" } 

Dies wird jedoch nicht arbeiten mit einer älteren Version von MongoDB, da sie kein preserveNullAndEmptyArrays Attribut unterstützen - ihre reguläreunwind Operation (ohne dieses Attribut) erzeugt Dokumentnummer 4 nicht aus die obige Auflistung. Hast du irgendwelche Ideen, wie man das mit Mongo3.0 implementiert?

+0

Verwandte http://stackoverflow.com/questions/13895006/unwind-empty-array – chridam

Antwort

1

Sie könnten eine Projektphase mit einer bedingten Anweisung hinzufügen:

db.lx.aggregate([{ 
      $project : { 
       "_id" : 1, 
       "tmp" : { 
        $cond : { 
         if : { 
          $eq : ["$tmp", []] 
         }, 
        then : [null], 
        else : "$tmp" 
       } 
      } 
     } 
    }, { 
     "$unwind" : { 
      path : "$tmp" 
     } 
    } 
]) 
Verwandte Themen