Upsert many documents in MongoDB and php

Viewed 3798

I try to import data from an external source into my mongodb with php. Every row from the external data is one mongodb document. Every row has an unique id called uid.

Now I am trying the following: I want to insert a new row, if no document with the same uid exists already (Upsert).

For a single document, I would do the following:

$collection->updateOne(
    ["uid" => "2"],
    ['$set' => [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ]],
    [
        "upsert" => true
    ]
);

Step 1:

Is it possible to override the complete document, not just set specific fields? Something like this:

$collection->updateOne(
    ["uid" => "2"],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ],
    [
        "upsert" => true
    ]
);

This is not working, since i get a First key in $update argument is not an update operator error. How to do it?

Step 2

For performance reasons, I want to use insertMany or updateMany function to bulk upsert multiple documents.

But what filter do I need for updateMany:

$db->updateMany(
    [???????],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "XXX"
    ],
    [
        "upsert" => true
    ]
);
1 Answers
Related