如何使用 php 在 MongoDB 文档中再添加一个字段? [英] How do I add one more field to MongoDB document using php?

查看:41
本文介绍了如何使用 php 在 MongoDB 文档中再添加一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像上传到现有文档.(通过再添加一个字段.)我正在通过电子邮件输入查找我的文档.这是我的代码:-

I am trying to upload an image to existing document.(By adding one more field.) I am finding my document through email input. Here is my code:-

<?php

 $errors = array();
 $data = array();
 $_POST = json_decode(file_get_contents('php://input'), true);

 $name=$__POST["mn"];
 $email=$__POST["me"];
 $i2u=$_POST["image2upload"];

 $binary = base64_decode($i2u);
 $filepath = 'images/newuploads/'.$name.'/'.$name.'.jpg';
 $imgurl = 'http://localhost/portfolio3/php/'.$filepath;
 file_put_contents($filepath, $binary);

 $m = new MongoClient();
 $db = $m->mydb2->mycol2;
 $foundRecord = $db->find(array('Email'=>$email));      

 $foundRecord->update(array(‘$set’ => array(‘uploadpic1’ => new MongoBinData(file_get_contents($imgurl)))));

?>

如何使用 php 在 MongoDB 文档中再添加一个字段?

How do I add one more field to MongoDB document using php?

推荐答案

首先,如果你只搜索一条记录,你应该使用 $db->findOne

Firstly, if you are searching for only one record, you should use $db->findOne

然后您可以执行以下操作:

You can then do the following:

 $foundRecord = $db->findOne(array('Email'=>$email));
 $foundRecord['uploadpic1'] = new MongoBinData(file_get_contents($imgurl);
 $db->save($foundRecord);

因为您使用了findOne,所以在使用$db->save($foundRecord);

Because you used findOne it will save to the fetched record instead of creating a new record when using $db->save($foundRecord);

否则,如果您想使用update,您需要在其中指定查询:

Else, if you want to use update you need to specify the query in it:

$db->update(array('Email'=>$email), array('$set' => array('uploadpic1' => new MongoBinData(file_get_contents($imgurl)))));

这篇关于如何使用 php 在 MongoDB 文档中再添加一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆