我试过这样做了很多种方式,从updateOne
,findOneAndUpdate
到insert
甚至试过bulkWrite
没有成功。
我所做的是我有两个集合的用户集合和image_upload集合。我将用户个人资料图像存储在image_upload中,并与用户上传的所有其他图像一起存储。
然后,我在用户集合中存储的是image_upload集合的ObjectID,它与用户在创建帐户时上载的图像相匹配(他们可以随时通过编辑配置文件上载新的配置文件图像)。
所以我想要的是能够更新ObjectId,因为我得到。
字段personal.profile_id
必须是一个数组,但在文档中是objectId类型。这是代码。我理想的是希望它具有ObjectID而不仅仅是一个字符串。
$db = static::db()->image_upload;
try {
$newdata = [
"data"=>
[
"url" => $publlic_url,
"type"=> $mimetype,
"date"=>new MongoDB\BSON\UTCDateTime(),
"profile_pic" => true
],
"uid"=>New MongoDB\BSON\ObjectId($uid)
];
$oauth_update = $db->insertOne($newdata);
$view['newdata'] = $newdata;
} catch(MongoResultException $e) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write($e->getDocument());
}
$ids = $oauth_update->getInsertedId();
$latest = $db->findOne(array("uid"=>New MongoDB\BSON\ObjectId($uid)));
// Check first, last and other personal details.
$db = static::db()->users;
try {
$newdata = ['$set' =>["personal.profile_id"=>New MongoDB\BSON\ObjectId($ids)]];
$member_profile = $db->findOneAndUpdate(
['kst'=>New MongoDB\BSON\ObjectId($uid)],
['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]],
[
'projection' =>
[ 'personal' => 1 ],
"returnDocument" => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
]);
} catch(MongoResultException $e) {
echo $e->getCode(), " : ", $e->getMessage(), "\n";
var_dump($e->getDocument());
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(array('code'=>$e->getCode(), 'message'=>$e->getMessage));
}
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($member_profile));
这是有点不清楚你实际问到的是什么。但是我看到它的方式是'$ ids = $ oauth_update-> getInsertedId()'实际上应该返回一个'ObjectId',因此不需要再次尝试“投射”这个值。所以你应该只是'['$''=> [“personal.profile_id”=> $ ids]]'。此外,“复数”的命名不是很清楚,它应该只是一个单数值。而对于“推送数组”,如果这是意图的话,你可以使用['$ each'](https://docs.mongodb.com/manual/reference/operator/update/each/)修饰符。 –