如何从 lumen 中的 mongo db 检索数据

how to retrieve data from mongo db in lumen

我有一个正在使用 mongo 数据库的流明项目,现在我想访问数据并对它们做一些逻辑我在 mongo 中的对象如下所示:

    _id: ObjectId('602cfb30bc865100073f0e56'),
    serviceType: 'normal',
    segment: 'Basic',
    steps: {
        'step1': 1,
        'step2': 2
    }

nnow 在我的 laravel 应用程序中,我这样做如下:

      $data = DiscountRule::first();
        dd($data);

结果如下:

 App\Models\Rule\DiscountRule {#183
  #collection: "discountRules"
  #connection: "mongodb"
  #dispatchesEvents: array:2 [
    "saved" => "App\Utility\Mongo\Listeners\ModelSaved"
    "deleted" => "App\Utility\Mongo\Listeners\ModelDeleted"
  ]
  -events: []
  #primaryKey: "_id"
  #keyType: "string"
  #parentRelation: null
  #table: "discountRules"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:4 [
    "_id" => MongoDB\BSON\ObjectId {#150
      +"oid": "602cfb30bc865100073f0e56"
    }
    "serviceType" => "pishropost-regular"
    "segment" => "Basic"
    "steps" => array:2 [
      "itemCount > 0 and itemCount <= 9" => 60000
      "itemCount > 9" => 0
    ]
  ]
  #original: array:4 [
    "_id" => MongoDB\BSON\ObjectId {#150}
    "serviceType" => "pishropost-regular"
    "segment" => "Basic"
    "steps" => array:2 [
      "itemCount > 0 and itemCount <= 9" => 60000
      "itemCount > 9" => 0
    ]
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [
    0 => "*"
  ]
}

现在它 return 将数据作为 array 但我想 return 作为对象,这样我就可以使用 $data->segment 并获取段中的数据.知道如何将来自 mongo 的数据 return 作为对象吗?

如您的 dd() 第一行所述。 return 的类型是 App\Models\Rule\DiscountRule。所有底层数组,都是 Laravel 模型在内部使用设置属性的方式。

所以你应该可以做到。

$rule = DiscountRule::first();
dd($rule->segment);