Stephen Romero
Stephen Romero

Reputation: 3032

MongoDB: Failed to parse objectId '' in $convert with no onError value: Invalid string length for parsing to OID, expected 24 but found 0

I am creating an aggregate query, but I'm running into an issue with some of my fields that need to be converted to ObjectIDs'. There are certain documents that do not have anything in the fields(null, ''), so I want to ignore those cases.

{
   "$project": {
    "Company": {
        "$toObjectId": "$Company"
    },
    "Lease": {
        "$toObjectId": "$Lease"
    },
    "Well": {
        "$toObjectId": "$Well"
   }
}

I've tried something similar to this:

{$ifNull: [{ $toObjectId: "$Company" }, ''] }

But I'm still receiving the error.

What is the best way to fix this?

Upvotes: 6

Views: 14995

Answers (2)

Pranav
Pranav

Reputation: 1

db.<collectionname>.aggregate([
  {
    $group: {
      _id: "$_id",
      avg_val: {
        $avg: {
          $toInt: {
            $trunc: {
              $multiply: [
                { $toDouble: "$value" },
                100
              ]
            }
          }
        }
      }
    }
  }
])

Upvotes: -3

Stephen Romero
Stephen Romero

Reputation: 3032

I realized I was using the short syntax of $toObjectId, which didn't have the options of onNull, or onError.

I needed to revert back to $convert:

{$convert: {input: '$Company', to : 'objectId', onError: '',onNull: ''}}

Source

Upvotes: 18

Related Questions