使用jenssegers/laravel-mongodb排序大数据报错,如何添加allowDiskUse:true?
Hey there! I’ve dealt with this exact memory limit error when sorting large datasets using the jenssegers/laravel-mongodb package, so I totally get how annoying it can be. Let’s break down how to add allowDiskUse: true to your queries in a few different scenarios:
Basic Query Builder or Eloquent Queries
The package actually provides a handy built-in method to enable disk use for sorting. You just need to chain the allowDiskUse() method onto your query before fetching results:
Using DB Facade
$largeDataset = DB::collection('your_collection_name') ->where('some_column', 'your_filter_value') ->orderBy('sort_column', 'desc') ->allowDiskUse() // This enables allowDiskUse: true ->get();
Using Eloquent Model
Same approach works with your Eloquent models too:
$largeDataset = YourModel::where('status', 'active') ->orderBy('created_at', 'asc') ->allowDiskUse() ->get();
Complex Aggregation Queries
If you’re working with MongoDB aggregations (like using aggregate()), you’ll need to pass the allowDiskUse option directly in the aggregation call. You can do this via the raw() method to access the underlying MongoDB collection instance:
// Define your aggregation pipeline $pipeline = [ ['$match' => ['category' => 'electronics']], ['$sort' => ['price' => -1]], // Add other pipeline stages as needed ]; // Execute aggregation with allowDiskUse enabled $results = DB::collection('products') ->raw(function ($collection) use ($pipeline) { return $collection->aggregate($pipeline, ['allowDiskUse' => true]); });
Why This Works
When you enable allowDiskUse: true, MongoDB will write temporary sorting data to disk instead of keeping it all in memory, which lets you bypass the default 100MB memory limit for sorting operations.
内容的提问来源于stack exchange,提问作者Mohsen Jalalian

