在MongoDB PHP中使用自定义_id进行Insert,InsertOne或upsert

时间:2018-08-26 08:09:44

标签: php mongodb

需要什么

我收到一个带有JSON对象的webhook,该对象具有唯一的id,它们用来引用特定对象的以后版本(它们是“采购订单ID”),如下所示:

$json_assoc_array = array (
    {
        'id' => "unique-id-1",
        'key_one' => "some value",
        'key_two' => "some value",
        'key_three' => "some value"
    },
    {
        'id' => "unique-id-2",
        'key_one' => "some value",
        'key_two' => "some value",
        'key_three' => "some value"
    },
    {
        'id' => "unique-id-3",
        'key_one' => "some value",
        'key_two' => "some value",
        'key_three' => "some value"
    }
);

我试图插入一个JSON对象作为文档,并将JSON对象的内部id值设置为MongoDB文档_id

我需要这样做,因为我希望插入的文档的id值是MongoDB集合中的唯一键/ ID。

这样,当我以后使用以下方式更新该对象时:

$json_assoc_array = array (
    {
        'id' => "unique-id-1",
        'key_one' => "new value",
        'key_two' => "some value",
        'key_three' => "some value"
    },
    {
        'id' => "unique-id-2",
        'key_one' => "some value",
        'key_two' => "new value",
        'key_three' => "some value"
    },
    {
        'id' => "unique-id-4",
        'key_one' => "some value",
        'key_two' => "some value",
        'key_three' => "some value"
    }
);

我需要能够用id = 1中的new value更新文档key_one,用id = 2中的new value更新文档key_two,并插入文档id = 4作为新文档。

我尝试过的

$json_assoc_array = json_decode($data, true);
$my_id = $json_assoc_array['id'];
$collection = $mongo->$mongo_db_name->products;

// The below works but it end up inserting the object as
// {
//     "_id": "5b821dfe3e2ffc4581116b24",
//     "id": unique-id-1,
//     "title": "\"Bubble Bumps\" Pipe",    //
//     ...
// }
// while the _id also needs to be `unique-id-1` from $json_assoc_array['id']
$result = $collection->insertOne($json_assoc_array);

// but this doesn't
$result = $collection->insertOne(array('_id' => my_id), $json_assoc_array);

// neither does this
$result = $collection->update(array('_id' => my_id), $json_assoc_array, ['upsert' => true]);

如何设置MongoDB唯一的_id作为对象的id,以便以后可以通过对象的id来更新文档

0 个答案:

没有答案