user3822551 user3822551 - 24 days ago 7
PHP Question

Get document id if it exists or insert it and return inserted document id if it does not exist

I use MongoDB together with PHP. I want to get id of document if it exists or insert a new document then return the id of inserted document.


collection like:

"_id": "57b4e71b4535e71816816183",
"tag": "tag1"
"_id": "57b4e71b4535e7181681612b",
"tag": "tag2"

I want to search by tag and get its id or insert it if does not exist. Could you please tell me how I can do that?


You can do this with the findAndModify() update operation that has the options new and upsert set to true. The new option set to true will return a single document with with the modifications made on the update.

With the specified upsert option set to true, findAndModify() either creates a new document if no documents match the query or updates a single document that matches the query.

The following mongo shell example demonstrates this:

var doc = { "tag": "tag3" };
var retval = db.tags.findAndModify({
    "query": doc,
    "update": { "$set": doc },
    "new": true, 
    "upsert": true

The equivalent PHP code follows:

$m = new Mongo;
$col = $m->selectDB("test")->tags;
$doc = array("tag" => "tag3");

$retval = $col->findAndModify(
    array("$set" => $doc),
        "upsert" => true,
        "new" => true,