将新值推送到 mongodb 内部数组 - mongodb/php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4638368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
push new value to mongodb inner array - mongodb/php
提问by Rizky Ramadhan
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?
但什么也没发生,有人知道怎么做吗?
回答by Justin Jenkins
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 $pushstatement, 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 ,
这应该有一个=>而不是 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...
但是,请注意,每次运行它时,如果您希望 MongoDB 仅插入“2”(如果“done_by”中尚不存在),则会插入另一个“2”,那么您应该使用$addToSet...
array('$addToSet' => array("done_by" => "2"))
This statement won't add 2 everytime, only the first time.
这个语句不会每次都加 2,只有第一次。
回答by Bob
$filter = array('_id'=>$id));
$update = array('$push'=>array('done_by'=>'2'));
$q->update($filter,$update);
回答by chx
回答by CKL
$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
以避免重复插入导致多个条目。
回答by Kirti Pawar
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")));