首页 > 解决方案 > 在mongo中如何匹配不是空元素列表的字段?

问题描述

我有字段 x 可以是[[], [], ...]或者["", "", ....]我想将它们过滤掉并保持文档至少有 1 个非空列表或 1 个非空字符串。例如[[], [1,2], [], ...]

标签: mongodbmongodb-queryaggregation-framework

解决方案


This is an aggregation query which filters out collection documents with the array field x, having elements with all empty strings or all empty arrays.

db.collection.aggregate([
{ 
    $addFields: { 
        filtered: { 
           $filter: { 
               input: "$x", 
               as: "e", 
               cond: {
                   $or: [
                       { $and: [ 
                          { $eq: [ { "$type": "$$e" }, "array" ] }, 
                          { $gt: [ { $size: "$$e" }, 0 ] } 
                       ] },
                       { $and: [ 
                          { $eq: [ { "$type": "$$e" }, "string" ] },
                          { $gt: [ { $strLenCP: "$$e" }, 0 ] } 
                      ] }
                   ]
               }
           }
        }
    }
},
{ 
    $match: { 
        $expr: { $gt: [ { $size: "$filtered" }, 0 ] }
    }
},
{ 
    $project: { filtered: 0 }
}
])

Reference: Various aggregation operators ($size, $type, $strLenCP, etc.) used.


推荐阅读