Mongo db 将新字段添加到集合中,如果字段已存在,则进行更新


Mongo db add new field to a collection and update if field already exists

我有 mongo 集合数组如下

[_id] => MongoId Object (
    [$id] => 7f841cef13cfcdba230019e2
)
[id] => 33
[name] => Adam
[table] => people

我想向现有字段添加字段计数

[_id] => MongoId Object (
    [$id] => 7f841cef13cfcdba230019e2
)
[id] => 33
[name] => Adam
[count] => 0
[table] => people

如果已设置 count ,则更新数组。

我使用了"更新"方法,但需要更改所有数组而不是一个字段。我如何使用 php 做到这一点?

如果您询问如何在不更改任何其他内容的情况下将count字段设置为给定值(如果尚不存在,则创建该字段),则可以使用 $set 运算符:

{ $set : { count: 0 }}   

使用update函数,例如:

 $collection->update('$set'=>array("_id" => new MongoID("id of document")), 
                     array("new fiels" => "value of field"));