sql >> Base de Datos >  >> NoSQL >> MongoDB

Obtenga solo el último elemento de la matriz mongoose

Es posible que desee utilizar la agregación mongodb (versión 3.2) $slice así:

Post.aggregate([
  { 
    $match: { 
      '_id.$oid': postId 
    }
  },
  { 
    $project: {
      comments: {
        $slice: [ "$comments", -1 ] 
      }
    }
  }
]);

En versiones anteriores de mongodb:

Post.aggregate([
  { 
    $match: { 
      '_id.$oid': postId 
    }
  },
  { 
    $unwind: "$comments"
  },
  {
    $group : {
      _id: "$_id.$oid",
      comment: { $last: "$comments" }
    }
  }
]);