将新值推送到mongodb内部数组-mongodb/php [英] push new value to mongodb inner array - mongodb/php

查看:58
本文介绍了将新值推送到mongodb内部数组-mongodb/php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongo中有此文档:

i have this document in mongo:

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

并且我想在"done_by"字段中添加另一个值,所以我期望的文档将是:

and i want to add another value to "done_by" field, so my expected document will be::

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

我试试这个:

$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")));

您的 $ push 语句存在问题,您没有在实际发送"done_by" 的情况下推送值"2"的"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" ...

这是问题所在...

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

这应该是 => 而不是

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

但是,请注意,每次运行此命令时,如果希望MongoDB仅插入"2"(如果在"done_by"中尚不存在),它将插入另一个"2",则应使用 $ addToSet ...

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 ...

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

此语句不会每次只加2.

This statement won't add 2 everytime, only the first time.

这篇关于将新值推送到mongodb内部数组-mongodb/php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆