如何在聚合函数mongodb上进行基于字符串长度的查询

如何在聚合函数mongodb上进行基于字符串长度的查询,mongodb,mongodb-query,Mongodb,Mongodb Query,我有这样的产品系列: { _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 Va

我有这样的产品系列:

{
  _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的所有产品。如果产品简单,我可以使用$where,例如:

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

如果我想显示不同的产品,我必须$unwind变量。但是,我还没有在聚合函数中找到像$where这样的运算符。任何ide我应该使用什么运算符根据字符串长度查找条形码?

好吧,我相信您可以使用
条件,如

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

最后,我有了答案

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

谢谢@Rahul,但它不起作用,我已经测试过了$or运算符必须有一个或多个表达式。'{“barCode.length==8”}不是表达式。