使用 php upsert 后获取 mongodb _id 对象
查询后是否可以获取新的/更新的_id? 示例代码:
$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );
$key 不持有新/旧 _id 对象,我假设 $data 也不会,因为它只是一条指令。
is it possible to get the new/updated _id after the query?
example code:
$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );
$key is not holding the new/old _id object and i assume that $data will not either because its just an instruction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是 - 可以使用单个查询。
MongoDB 包含
findAndModify< /code>
命令可以自动修改文档并返回它(默认情况下它实际上返回修改之前的文档)。
PHP 驱动程序在集合类上没有包含一个方便的方法(但是 - 请查看此错误 ),但它仍然可以使用(请注意,我的 PHP 很糟糕,所以我很可能在以下代码片段中犯了语法错误):
Yes -- It is possible using a single query.
MongoDB includes a
findAndModify
command that can atomically modify a document and return it (by default it actually returns the document before it's been modified).The PHP drivers don't include a convenient method for this on the collection class (yet -- check out this bug), but it can still be used (note that my PHP is terrible, so I may very well have made a syntax error in the following snippet):
以防万一有人像我一样偶然发现这个问题,当你调用 MongoCollection->save(); 时,Mongo 实际上会修改输入数组。 - 将 id 添加到末尾。
因此,如果您调用:
您将获得该对象的 mongo id。
Just in case someone stumbles across this question like I did, Mongo will actually modify the input array when you call MongoCollection->save(); - appending the id to the end.
So, if you call:
You will have the mongo id for that object.
我遇到了这个问题,并通过在 upsert 后查询 _id 来解决它。我想我应该添加一些我的发现,以防它们对来这里寻找信息的人有用。
当 upsert 导致在集合中创建新文档时,返回的对象包含 _id(这是示例的 print_r):
您可以从中获取 _id:
但是,如果 upsert 导致现有文档被更新,则返回的对象不包含_id。
I ran into this issue and worked around it by querying back the _id after the upsert. I thought I'd add some of my findings in case they're useful to anyone who comes here searching for info.
When the upsert results in a new document being created in the collection, the returned object contains the _id (here's a print_r of an example):
You can get the _id from this:
However, if the upsert resulted in an existing document being updated then the returned object does not contain _id.
试一试:
假设传递的
$id
为 null,则会创建一个新的MongoId
,否则它只会转换现有的$id
到 MongoId 对象。希望这有帮助:D
Give this a shot :
So lets say the passed
$id
is null, a freshMongoId
is created, otherwise it just converts the existing$id
to a MongoId object.Hope this helps :D
update 方法返回一个数组,其中包含 UPSERTED 文档的 ID:
The update method returns an array with the ID of the document UPSERTED:
您还可以在更新/更新插入中将 fsync 设置为 true,以将 _id 返回到已传递给更新的对象。
You can also set fsync to true in an update/upsert, to get the _id returned to the object that has been passed to the update.