mongodbaggregate

How to null-safe and missing-field-safe determine max length of field in mongodb?


I want to get the max length of a string field in the collection in mongodb 7.0

In SQL something like that

SELECT (MAX(LENGTH(street)) FROM persons WHERE (street is NOT NULL)

The field "street" can be NULL, not present or have a real content.

I tried this

db.getCollection("persons").aggregate([
    {
        $match: {
            "street": {
                $exists: true
            }
        },
        $project: {
            street: 1,
            l: {$strLenCP: "$street"}
        }
    }
]);

But I get this error

A pipeline stage specification object must contain exactly one field

I know $strLenCP is "not null safe", what am I doing wrong?


Solution

  • You missed the curly brackets:

    db.getCollection("persons").aggregate([
      {
        $match: {
          "street": { $exists: true }
        }
      },
      {
        $project: {
          street: 1,
          l: { $strLenCP: "$street" }
        }
      }
    ])
    

    Regarding your actual question, have a look at Or with If and In mongodb