Home > OS >  $sample aggregate not functioning correctly in MongoDB
$sample aggregate not functioning correctly in MongoDB

Time:09-23

i am trying to grab a random document from my collection and I keep receiving the error:

PlanExecutor error during aggregation :: caused by :: The argument to $size must be an array, but was of type: missing

obviously not trying to use the $size aggregate just the parameter with the $sample aggregate.

[{
 $project: {
  _id: '$_id',
  sender_id: '$sender_id',
  date_time: '$date_time',
  numberOfLikes: {
   $size: '$favorited_by'
  }
 }
}, {
 $match: {
  numberOfLikes: {
   $gte: 9
  }
 }
}, {
 $lookup: {
  from: 'UsedClessics',
  localField: '_id',
  foreignField: 'reply_id',
  as: 'UsedClessics'
 }
}, {
 $match: {
  'UsedClessics.type': {
   $ne: 'reply'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: 'system'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: '848846'
  }
 }
}, {
 $sample: {
  size: 1
 }
}]

CodePudding user response:

The error is NOT thrown because of $sample stage, but because of the first $project stage.

There, you are fetching the size of the favorited_by property, and apparently some of the documents is missing that field.

Try to change your first $project stage like this:

{
  $project: {
    _id: "$_id",
    sender_id: "$sender_id",
    date_time: "$date_time",
    numberOfLikes: {
      $cond: {
        if: {
          $isArray: "$favorited_by"
        },
        then: {
          $size: "$favorited_by"
        },
        else: 0
      }
    }
  }
}
  • Related