2016-08-23 79 views
1

字符串的長度使查詢我的產品的集合是這樣的:如何基於聚合函數的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' 
} 

我希望顯示有條形碼長度8.如果只是簡單的產品所有的產品,我可以用$其中,例如:

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

如果我想顯示各種產品,我必須$放寬變體。但是,我沒有在聚合函數中找到像$這樣的運算符。任何我應該用什麼操作符來查找基於字符串長度的條形碼?

回答

1

好吧,我相信你可以使用一個OR條件像

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

謝謝@Rahul,但它不會工作,我測試了它。 $或操作符必須有一個或多個表達式。 '{「barCode.length == 8」}「不是expresion。 –

2

最後,我找到了答案。

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'}}}, 
])