Wang
Wang

Reputation: 8163

in mongo how to match a field that is not list of empty elements?

I have field x which can be [[], [], ...] or ["", "", ....] I want to filter them out and keeps the document at least have 1 non-empty list or 1 non-empty string. for example [[], [1,2], [], ...]

Upvotes: 0

Views: 43

Answers (1)

prasad_
prasad_

Reputation: 14287

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.

Upvotes: 1

Related Questions