查找所有文档中特定键的最高值

时间:2016-10-31 14:36:01

标签: php json mongodb

我有一个Laravel应用程序,可以在其中输入(excel)文档,这些文档将被解析为JSON以上传到MongoDB。我想调整我的控制器,以便项目不能重复。我想在关键' project_id'上查看这个。当' project_id'在JSON中是唯一的,该文件将被输入数据库中。如果' project_id'在数据库中,我想返回最高值+1,告诉用户他们可以使用这个' project_id'。我的控制器看起来像这样:

public function upload() {
        $file = array('thefile' => Input::file('thefile'));
        $rules = array('excel' => 'excel');
        $validator = Validator::make($file, $rules);
        if ($validator->fails()) {
            return Redirect::to('UploadExcelFile')->withInput()->withErrors($validator);
        }
        else {
            if (Input::file('thefile')->isValid()) {
                $destinationPath = 'uploads';
                $fileName = Input::file('thefile')->getClientOriginalName();
                Input::file('thefile')->move($destinationPath, $fileName);
                Session::flash('success', 'Upload successfully');
                $tmp = exec("python public/scripts/ExcelToJSON3.py $fileName");
                //      Getting the Project ID from the file that is uploaded
                $str = file_get_contents($tmp);
                $json = json_decode($str);
                $project_id = $json[0]->project_id;
                //      Opening a connection with the database
                $m = new MongoClient();
                $db = $m->database;
                $collection = $db->test;
                //      Find a document with the same Project ID
                $cursor = $collection->findOne(array("project_id" => $project_id));
                if (empty($cursor)) {
                    $upload = exec("mongoimport --db database--collection test --type json --file " . $tmp . " --jsonArray");
                } else {
                    $highest_projectid = '';
                    $val = $collection->find(array(), array('project_id' => 1))->sort(array('project_id' => -1))->limit(1);
                    foreach ($val as $doc)
                    {
                        $highest_projectid = implode(',',$doc);
                    }
                    return redirect('dashboard/input')->with('status', 'The file which you tried to upload already exist on our database. '.$highest_projectid.' ');
                }
                return \View::make('UploadExcelFile')->with(array('fileName' => $fileName, 'tmp' => $tmp  ));
            }
            else {


 // sending back with error message.
            Session::flash('error', 'uploaded file is not valid');
            return Redirect::to('UploadExcelFile');
        }
    }

我收到的消息是:

  

您尝试上传的文件已存在于我们的数据库中。   581749cfa0e57d26d69edde9,3

(3是最高值)

但_id值也会被打印出来?有人能帮助我吗?

0 个答案:

没有答案