Mark
Mark

Reputation: 33571

Mongodb php get id of new document?

Creating a document:

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

How to get the new document's id?

Upvotes: 36

Views: 34950

Answers (4)

the_root
the_root

Reputation: 339

This works for me:

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

Upvotes: 25

BbopLifa
BbopLifa

Reputation: 130

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

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

Upvotes: 1

user133408
user133408

Reputation:

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.

Upvotes: 34

Theo
Theo

Reputation: 132882

According to the docs the array you pass to insert will be amended with an _id field:

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

Upvotes: 62

Related Questions