我對 MongoDB 和 PHP 非常陌生,我正在嘗試將一個物件添加到一個已經存在的檔案中。問題是我看到這個$push變數被大量使用,但似乎無法讓它在我自己的專案中作業。
我的檔案
{
"_id": {
"$oid": "622dfd21f8976876e162c303"
},
"name": "testuser",
"password": "1234"
}
可以說這是我收藏中的一個檔案users。我想添加一個物件,domains該物件在該物件內使用一些資料呼叫,如下所示:
"domains": {
"name": "example.com"
}
我嘗試了很多不同的東西,但它們似乎不起作用。 我嘗試了什么: 我嘗試過這樣做:
$doc = array(
"domains" => array("name": "nu.nl")
);
$collection->insert($doc);
像這樣:
$insertOneResult = $collection->updateOne(
{"name" : "testuser"},
'$push': {"domains": {"name": "example.com"}}
);
但它們都不起作用。誰能幫我解決這個問題或評論一個可以幫助我解決這個問題的鏈接?提前致謝!
uj5u.com熱心網友回復:
你真的很親近!
db.users.update({
"name": "testuser"
},
{
"$push": {
"domains": {
"name": "example.com"
}
}
})
在mongoplayground.net上試試。
php自古以來我就沒有使用過gforge,但我對使用php連接器的猜測是(歡迎更正!):
<?php
$collection = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
['name' => 'testuser'],
['$push' => ['domains' => ['name' => 'example.com']]]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/444044.html
上一篇:如何在郵遞員中發送物件陣列?
