Mongodb php 获取新文档的 id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4525556/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:18:36  来源:igfitidea点击:

Mongodb php get id of new document?

phpmongodbmongodb-php

提问by Mark

Creating a document:

创建文档:

$db->collection->insert($content);
// $newDocID = ???

I'm trying to get the new document's id. How? Thanks.

我正在尝试获取新文档的 ID。如何?谢谢。

回答by Theo

According to the docsthe array you pass to insertwill be amended with an _idfield:

根据文档,您传递给的数组insert将使用一个_id字段进行修改:

$db->collection->insert($content);
$newDocID = $content['_id'];

回答by Mark

You can also get _id beforeinsert. Just add _id field to document with new MongoId ie.

您还可以插入之前获取 _id 。只需使用新的 MongoId 将 _id 字段添加到文档中即可。

$content['_id'] = new MongoId();
$db->collection->insert($content);

Also there are nice benefits of this:

这也有很好的好处:

  1. You don't need fsync flag like posted in comment by ZagNut in previous answer. So you don't need to wait for reply from DB.
  2. You don't need to actually insert anything to DB to get id. So you can prepare some related objects and then insert or not insertthem - somewhat like transactions which mongo does not support (yet?).
  3. You actually cangenerate id in your application, not in db, So you can do whatever you want before or after insert.
  1. 您不需要像 ZagNut 在之前的答案中发表在评论中的 fsync 标志。所以你不需要等待 DB 的回复。
  2. 您实际上不需要向 DB 插入任何内容来获取 id。所以你可以准备一些相关的对象,然后插入或不插入它们 - 有点像 mongo 不支持的事务(还?)。
  3. 你实际上可以在你的应用程序中生成 id,而不是在 db 中,所以你可以在插入之前或之后做任何你想做的事情。

回答by the_root

This works for me:

这对我有用:

$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();

回答by BbopLifa

 $newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
 $strId = $newDocument['_id']->{'$id'};

http://php.net/manual/en/mongocollection.findandmodify.php

http://php.net/manual/en/mongocollection.findandmodify.php