diff --git a/src/Increment.php b/src/Increment.php new file mode 100644 index 0000000..16add10 --- /dev/null +++ b/src/Increment.php @@ -0,0 +1,22 @@ +name = $propertyName; + $this->by = $incrementBy; + } + + public function asArray(): array + { + return [ + "\$inc" => [$this->name => $this->by] + ]; + } +} diff --git a/src/QueryBuilder.php b/src/QueryBuilder.php index b5f7cb9..fbd886c 100644 --- a/src/QueryBuilder.php +++ b/src/QueryBuilder.php @@ -258,7 +258,7 @@ public function orWhereEndsWith(string $key, $value): self private function buildWhere(string $prefix, $key, $operator = null, $value = null): void { // Assume that the operator is = - if ($value === null && !in_array($operator, array_keys(self::$mongoOperatorMap))) { + if ($value === null && !in_array((string)$operator, array_keys(self::$mongoOperatorMap))) { $value = $operator; $operator = "="; } @@ -398,7 +398,28 @@ public function update($update): UpdateResult { if (empty($this->filters)) throw new Exception("You must set a filter (where query) to update records."); - return $this->collection->updateMany($this->getNormalizedFilters(), ["\$set" => $update]); + + $pipeline = []; + + $inc = []; + $set = \array_filter($update, function($value) use (&$inc) { + // Filter out Increments + if ($value instanceof Increment) { + $inc[] = $value->asArray(); + return false; + } + return true; + }); + + // Add set to the pipeline + if (!empty($set)) + $pipeline["\$set"] = $set; + + // Add all increments to the pipline + if (!empty($inc)) + $pipeline["\$inc"] = array_merge(...array_column($inc, "\$inc")); + + return $this->collection->updateMany($this->getNormalizedFilters(), $pipeline); } public function delete(): DeleteResult diff --git a/src/RawFilter.php b/src/RawFilter.php index 1886027..612af9c 100644 --- a/src/RawFilter.php +++ b/src/RawFilter.php @@ -29,7 +29,7 @@ public static function fromCollectionOfRawFilters($filters): self public function push($filter): self { - return $this->pushMany([$filter]); + return $this->pushMany($filter); } public function pushMany($filters): self