2016-08-23 68 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'}}}, 
])