2016-08-23 5 views
1

I Produktkollektionen wie dieses:Wie Abfrage machen, basierend auf String-Länge auf Aggregatfunktion mongodb

{ 
    _id: 'prod_id_1', 
    type: SIMPLE, 
    name: 'Product Simple 1', 
    barcode: '00000004' 
}, 
{ 
    _id: 'prod_id_2', 
    type: SIMPLE, 
    name: 'Product Simple 2', 
    barcode: '00000005' 
}, 
{ 
    _id: 'prod_id_3', 
    type: VARIED, 
    name: 'Product Varied 1', 
    variants: [ 
    { 
     id: 'variant_aqua_base_m_size', 
     name: 'Variant AquaM', 
     barcode: '121200000005' 
    }, 
    { 
     id: 'variant_aqua_base_m_size', 
     name: 'Variant AquaM', 
     barcode: '00000007' 
    } 
    ] 
}, 
{ 
    _id: 'prod_id_4', 
    type: SIMPLE, 
    name: 'Product Simple 4', 
    barcode: '121200000008' 
} 

Ich möchte alle Artikel angezeigt werden, die Barcode-Länge 8. Wenn nur Produkt einfach hat, kann ich $ verwenden wo, beispiel:

db.product.find({$where: "this.barCode.length == 8", 'barCode': {$exists: true}}) 

Wenn ich Produkt unterschiedlich darstellen möchte, muss ich die Varianten abwickeln. Aber ich habe keinen Operator wie $ in Aggregatfunktion gefunden. Welcher Operator sollte ich verwenden, um einen Barcode anhand der Stringlänge zu finden?

Antwort

1

Nun, ich glaube, Sie einen OR Zustand wie

db.product.find({"$or": [{"barCode.length == 8"}, {"variants.barCode.length == 8"}], 'barCode': {$exists: true}}) 
+0

Dank @Rahul, aber es wird nicht funktionieren, ich habe es getestet. $ oder operator muss einen oder mehrere Ausdrücke haben. '{"barCode.length == 8"}' ist kein Ausdruck. –

2

Schließlich verwenden kann ich die Antwort.

db.product.aggregate([ 
{"$project":{ 
     "u_barCode": { 
      "$let": { 
       "vars": { 
        "variantBarCode": { 
         "$cond": [ 
          {"$eq": ["$variants", null]}, 
          [], 
          {"$ifNull": ["$variants.barCode", [null]]} 
         ] 
        }, 
        "barCode": {"$ifNull": ["$barCode", null]} 
       }, 
       "in": { 
        "$cond": [ 
         {"$eq": ["$$variantBarCode", [null]]}, 
         {"$map": { 
          "input": {"$literal": [null]}, 
          "as": "el", 
          "in": "$$barCode" 
         }}, 
         "$$variantBarCode" 
        ] 
       } 
      } 
     }, 
     "type" : "$type" 
    } 
}, 
{$unwind : "$u_barCode"}, 
{$match: {u_barCode: {$regex: '^[0-9]{8}$', $options: 'm'}}}, 
]) 
Verwandte Themen