laravel-mongodb: Raw query that returns select fields

I’m using the query to organize places by location but return only a few columns/fields from each object in the collection. Based on my understanding of Mongo queries, the raw statement in the code below should work, but it returns an empty array. If I remove the name field it returns all the objects in the collection as expected, but not as desired.

There’s several open issues on this question with no relevant responses. Even a “hey idiot, do this” would be nice.

$shops_sorted = Shop::raw(function($collection) use ($latitude, $longitude) {
                return $collection->find([
                    'status' => 'show',
                    'loc'    => [
                        '$near' => [
                                $longitude, 
                                $latitude
                                ]
                    ]
                ],
                [
                'name'     => 1
                ]
                );
            })->toArray();

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 16 (2 by maintainers)

Most upvoted comments

with the package probably like this

$shops_sorted = Shop::raw(function($collection) use ($latitude, $longitude) { 
    return $collection ->find(['status' => 'show', 'loc' => [ '$near' => [ $longitude, $latitude ] ] ], ['field1' => true, 'field2' => true] );
})->toArray();

Try something like this is new driver version

/* Select documents matching given criteria */
$filter = [
    'status' => 'show',
//    ...
];

$options = [
    /* Only return following fields from matching documents */
    'projection' => [
        'title' => true,
        'article' => true,
    ],
    /* Return the documents in specified order */
    'sort' => [
        // specify your sort criteria here
    ],
];

$query = new MongoDB\Driver\Query($filter, $options);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$cursor = $manager->executeQuery($collection, $query);

foreach($cursor as $document) {
    // document here should have only specified fields along with id
    var_dump($document);
}

hey did you tried this

$shops_sorted = Shop::raw(function($collection) use ($latitude, $longitude) { return $collection ->find([ 'status' => 'show', 'loc' => [ '$near' => [ $longitude, $latitude ] ] ], [ 'name' => 1 ] ) ->fields(['field1' => true, 'field2' => true]) })->toArray();