Mongodb php get id of new document?

后端 未结 4 1290
不知归路
不知归路 2020-12-29 19:39

Creating a document:

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

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

4条回答
  •  萌比男神i
    2020-12-29 20:01

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

    $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 insert them - somewhat like transactions which mongo does not support (yet?).
    3. You actually can generate id in your application, not in db, So you can do whatever you want before or after insert.

提交回复
热议问题