【问题标题】:How to get the size of an array in document using MongoDB Laravel Query如何使用 MongoDB Laravel Query 获取文档中数组的大小
【发布时间】:2020-07-21 21:15:01
【问题描述】:

我有数据

    {
  "_id": {
    "$oid": "5e8e1be5a78b4479443eae43"
  },
  "vehicle_component_id": 3,
  "damages_types": [
    1,
    7
  ],
  "mileages": [
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0"
  ],
  "damages": {
    "1": {
      "upper_bound": [
        null
      ],
      "damages": [
        "0"
      ],
      "lower_bound": [
        null
      ]
    },
    "7": {
      "upper_bound": [
        null
      ],
      "damages": [
        "0"
      ],
      "lower_bound": [
        null
      ]
    }
  },
  "created_at": "2020-04-08 20:45:57",
  "updated_at": "2020-04-08 20:45:57"
}

并尝试获取 mongo 查询的里程数组的大小或长度

db.vehicle_component_damages_values.aggregate(
{ $match: { vehicle_component_id: 3}  },
{$project: { count: { $size:"$mileages" }}}
)

它按预期返回 10,但在尝试使用 jenssegers/laravel-mongodb 时像

            $query = DB::connection($this->mongoCon)->collection($this->table)->raw(function($collection) use ($vehicleComponentId) {

            return $collection->aggregate([
                ['$match' => ['vehicle_component_id' => $vehicleComponentId]],
                [
                    '$project' => [
                        'count' => [
                            '$size' => '$mileages'
                        ]
                    ]
                ],
            ]);
        });

它回来了

MongoDB\Driver\Cursor {#550}

【问题讨论】:

  • 尝试添加->toArray()
  • 它有效,但结果也来自类型“MongoDB\Model\BSONDocument”,->toArray() 无法处理它

标签: laravel mongodb eloquent


【解决方案1】:

所以我的最终代码是

public function findMileagesSizeByVehicleComponentId($vehicleComponentId)
{
    try {

        $cursor = DB::connection($this->mongoCon)->collection($this->table)->raw(function ($collection) use (
            $vehicleComponentId
        ) {

            return $collection->aggregate([
                ['$match' => ['vehicle_component_id' => $vehicleComponentId]],
                [
                    '$project' => [
                        'count' => [
                            '$size' => '$mileages',
                        ],
                    ],
                ],
            ]);
        });

        $result = $cursor->toArray();

        if (!empty($result)) {
            if (sizeof($result) == 1) {
                return iterator_to_array($result[0])['count'];
            } else {
                throw new ValidationError("Result has multiple counts please check your query.");
            }
        } else {
            return 0;
        }


    } catch (\Throwable $e) {
        return Error::handel($e);
    } catch (\Exception $e) {
        return Error::handel($e);
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-27
    • 2021-02-17
    • 2021-02-11
    • 2016-11-19
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多