简体   繁体   English

将新值推送到mongodb内部数组 - mongodb / php

[英]push new value to mongodb inner array - mongodb/php

i have this document in mongo: 我在mongo中有这个文件:

{
   "_id": ObjectId("4d0b9c7a8b012fe287547157"),
   "done_by": ["1"]
}

and i want to add another value to "done_by" field, so my expected document will be:: 我想在“done_by”字段中添加另一个值,所以我的预期文档将是::

{
   "_id": ObjectId("4d0b9c7a8b012fe287547157"),
   "done_by": ["1","2","3"]
}

i try this: 我试试这个:

$conn = new Mongo();
$q = $conn->server->gameQueue;
$id = new MongoId("4d0b9c7a8b012fe287547157");
$q->update(array("_id"=>$id),array('$push' => array("done_by","2")));

but nothing happens, anyone know how to do this? 但没有任何反应,任何人都知道如何做到这一点?

Since neither of these answers are actually telling you what's wrong here ... 既然这些答案都没有告诉你这里有什么问题......

$conn = new Mongo();
$q = $conn->server->gameQueue;
$id = new MongoId("4d0b9c7a8b012fe287547157");
$q->update(array("_id"=>$id),array('$push' => array("done_by","2")));

There is a problem with your $push statement, you are not pushing "done_by" with a value of "2" you are actually sending "done_by" and "2" ... 你的$ push语句有问题,你没有推送值为“2”的“done_by”你实际发送的是“done_by” “2”......

Here is the issue ... 这是问题......

array('$push' => array("done_by","2"))

This should have a => not a , 这应该有一个=>不是

array('$push' => array("done_by" => "2"))

However, note that every time you run this it will insert another "2" if you want MongoDB to only inset "2" if it doesn't already exist in "done_by" then you should use $addToSet ... 但是请注意,每次运行它都会插入另一个“2”,如果你想让MongoDB只插入“2”,如果它在“done_by”中不存在那么你应该使用$ addToSet ...

array('$addToSet' => array("done_by" => "2"))

This statement won't add 2 everytime, only the first time. 此声明不会每次都添加2,而只是第一次。

$filter = array('_id'=>$id));
$update = array('$push'=>array('done_by'=>'2'));
$q->update($filter,$update);

$push => array('done_by' => '2')

So says the manual : { $push : { field : value } } 所以手册说: { $push : { field : value } }

$filter = array('_id'=>$id));
$update = array('$addToSet'=>array('done_by'=>'2'));
$q->update($filter,$update);

When you need to update use $addToSet so you avoid duplicate inserts which leads to multiple entries. 当您需要更新时使用$addToSet以避免重复插入,从而导致多个条目。

u can use as this : 你可以这样使用:

$conn = new Mongo();
$q = $conn->server->gameQueue;
$id = new MongoId("4d0b9c7a8b012fe287547157");
$q->update(array("_id"=>$id),array('$addToSet' => array("done_by","2")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM