MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Ottieni solo l'ultimo elemento dell'array mangusta

Potresti voler utilizzare l'aggregazione mongodb (versione 3.2) $slice così:

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

Nelle versioni precedenti di mongodb:

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