xp-forge / mongodb

MongoDB for the XP Framework
0 stars 0 forks source link

Select a single document #46

Open thekid opened 7 months ago

thekid commented 7 months ago

Currently, the pattern is first() ?? throw:

// Using find()
$post= $posts->find(new ObjectId($id))->first() ?? throw new Error(404);

// Using aggregate()
$cursor= $posts->aggregate([
  ['$match' => ['_id' => new ObjectId($id), 'state' => null, 'published' => ['$ne' => null]]],
  ['$lookup' => [
    'from'         => 'network',
    'localField'   => 'published.by.id',
    'foreignField' => '_id',
    'as'           => 'publisher',
  ]],
  ['$addFields' => ['publisher' => ['$arrayElemAt' => ['$publisher', 0]]]],
]);
$post= $cursor->first() ?? throw new Error(404);

Can we create a utility method for this like single()?

// Passing string|ObjectId will find() by _id
$post= $posts->single(new ObjectId($id));

// Passing an array will use aggregate()
$post= $posts->single([
  ['$match' => ['_id' => new ObjectId($id), 'state' => null, 'published' => ['$ne' => null]]],
  ['$lookup' => [
    'from'         => 'network',
    'localField'   => 'published.by.id',
    'foreignField' => '_id',
    'as'           => 'publisher',
  ]],
  ['$addFields' => ['publisher' => ['$arrayElemAt' => ['$publisher', 0]]]],
]);

Should there also be an all() method to select all, and an optional() to select zero or one?

thekid commented 7 months ago

See also https://stackoverflow.com/questions/31171451/getting-a-single-object-from-mongodb-in-c-sharp

thekid commented 7 months ago

Called get() here: https://github.com/mono-js/mongodb-utils