使用 PHP 在 Mongo DB 中的文档内添加数据 [英] Add data inside documents in Mongo DB using PHP

查看:37
本文介绍了使用 PHP 在 Mongo DB 中的文档内添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 PHP 脚本在 Mongo 数据库 中插入数据,在 year 明智的文档中,使其看起来像这样(一个文档中的所有年份);

I want to insert data in Mongo database using PHP script, in year wise documents so that it may look like this (All years in one document);

cars{
        2017{
            car=Motorolla
            color = blue
        }
        2016{
            car=Toyota
            color = green
        }
        2015{
            car=Corolla
            color = black
        }
    }

我想添加文档但它提示

文档不能有 $ 前缀的字段名称:$years[0]

Document can't have $ prefixed field names: $years[0]

是否可以使用 PHP 在 Mongo 中创建这样的模式?

Is it possible to make such schema in Mongo using PHP?

代码

<?php
    try {        
        $car = 'Motorolla';
        $color = 'blue';

        //$car = 'Toyota';
        //$color = 'green';

        //$car = 'Corolla';
        //$color = 'black';

        $years = array(2017, 2016, 2015);       
        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;
        $document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color];   // Making a query type

        try {
            $bulkWriteManager->insert($document);   // Inserting Document
            echo 1;           
        } catch(MongoCursorException $e) {
            /* handle the exception */
            echo 0;
        }

        $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager);  // Going to DB and Collection

    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n"; 
        echo "It failed with the following exception:\n";       
        echo "Exception:", $e->getMessage(), "\n";


    }

?>

我不想一次添加整个汽车对象.我想每次都添加 Year 对象.任何帮助将是可观的.任何相关的答案,以便我可以根据年份从 Mongo 数据库 中获取数据?

I do not want to add whole car object at once. I want to add Year object every time. Any help will be appreciable. OR Any relative answer so that I may get the data from Mongo Database according to the year?

编辑 1

第一次创作.- 感谢@Veeram

<?php
    try {        
        $car = 'Malibu';
        $color = 'red';
        $years = array(2017);       

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;
        //{"car":"chevy", "color":"black", year: 2017}
        $insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
        try {
            $bulkWriteManager -> insert($insert); // Inserting Document
            echo 1;
        } catch (MongoCursorException $e) {
            echo 0;
        }
        $manager->executeBulkWrite('dbName.mycol', $bulkWriteManager);  // Going to DB and Collection           
    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n"; 
        echo "It failed with the following exception:\n";       
        echo "Exception:", $e->getMessage(), "\n";
        echo "In file:", $e->getFile(), "\n";
        echo "On line:", $e->getLine(), "\n";    
    }
?>

更新 - 感谢@Veeram

<?php
    try {        
        $car = 'ChangedCar';
        $color = 'changedColor';
        $years = array(2017);

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;

        $query = ['cars.year' => $years[0]]; 

        //{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
        $update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
        try {
            $bulkWriteManager->update($query, $update);   // Inserting Document        
        } catch(MongoCursorException $e) {

        }
        $manager->executeBulkWrite('dbName.mycol', $bulkWriteManager);  // Going to DB and Collection
    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n"; 
        echo "It failed with the following exception:\n";       
        echo "Exception:", $e->getMessage(), "\n";
    }
?>

这段代码的问题是它第一次成功插入了数据,但是当我更新数据时它没有更新它.

示例:有一个名为 cars 的文档.在一个文档中插入带有年份对象的数据.假设对象是 2017 年,它包含颜色和汽车模型.如下图所示;(多个带有年份的对象.年份在整个文档中是唯一的.)

Example: There is a document named as cars . Insert the data with object of year in one document. Let's say the Object is 2017, it contains color and car Model. As showing below; (Multiple objects with years. Year is unique in whole document.)

cars{
        2017{
            car=Motorolla
            color = blue
        }
        2016{
            car=Toyota
            color = green
        }
        2015{
            car=Corolla
            color = black
        }
    } 

如果我想更新,只需创建一个 2017 对象,例如 2017{car=Updated-Motorolla color =Updated-blue} 并插入到文档中.它应该只更新文档中的 2017 年对象.

If I want to update just make an object of 2017 like 2017{car=Updated-Motorolla color =Updated-blue} and insert in the document. It should update only the year 2017 object in side the document.

 cars{
            2017{
                car=Updated-Motorolla
                color =Updated-blue
            }
            2016{
                car=Toyota
                color = green
            }
            2015{
                car=Corolla
                color = black
            }
        } 

推荐答案

您可以尝试这样的操作.仅将 off key 作为值来执行所有 Mongo db 操作是不可能的.

You can try something like this. Its not possible to perform all the Mongo db operations just based off key as a value.

第一个解决方案是为了贴近 OP 的设计而编写的.

The first solution is written to stay close to OP's design.

假设您可以为 year 添加一个键.

Assuming you can add a key to the year.

{
  "cars": [{
      "year": "2017",
      "data": [{
          "car": "Motorolla",
          "color": "blue"
      }]
  }, {
      "year": "2016",
      "data": [{
          "car": "Toyota",
          "color": "green"
      }]
  }]
}

通过其值可以轻松引用年份.

Makes it easy to reference the year by its value.

例如将一个新值添加到 year 2017 的 data 数组中.您可以尝试以下代码.

For example to add a new value into the data array for year 2017. You can try the below code.

使用更新位置 $ 运算符.

Uses update positional $ operator.

query 部分引用存储 2017 记录的数组.

query part to reference the array where 2017 record is stored.

update 部分使用 push 将新的 car 记录添加到 的现有 data 数组2017 行.

update part using push to add the new car record to the existing data array for 2017 row.

<?php
    try {        
        $car = 'Malibu';
        $color = 'blue';
        $years = [2017];

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;

        //{"cars.year":2017}
        $query = ['cars.year' => $years[0]]; 

        //{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
        $update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];

        try {
            $bulkWriteManager->update($query, $update);  // Update Document
            echo 1;           
        } catch(MongoCursorException $e) {
            /* handle the exception */
            echo 0;
        }

        $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager);  // Going to DB and Collection

    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n"; 
        echo "It failed with the following exception:\n";       
        echo "Exception:", $e->getMessage(), "\n";
    }

?>

要按年份访问数据,您可以运行以下查询.

For accessing data by year you can run below query.

使用查询位置$运算符使用查询部分查找数组索引并在投影部分引用该值.

Use query positional $operator to find the array index using the query part and reference that value in projection part.

db.collection.find({"cars.year":2017}, {"cars.$.data":1});

替代解决方案:

这会像插入一样处理一切

This will take care of everything as just inserts

最好将每个汽车条目保存在自己的文档中.

You are better off saving each car entry in its own document.

{ "year" : 2017, "car" : "Motorolla", "color" : "blue" }
{ "year" : 2016, "car" : "Toyota", "color" : "green" }
{ "year" : 2015, "car" : "Corolla", "color" : "black" }

对于您可以使用的每个条目:

For each entry you can use:

db.collection.insert({"year":2017,  "car":"Motorolla", "color":"blue"});

PHP 代码:

 //{"car":"chevy", "color":"black", year: 2017}
 $insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];

 try {
    $bulkWriteManager - > insert($insert); // Inserting Document
    echo 1;
 } catch (MongoCursorException $e) {
    /* handle the exception */
    echo 0;
 }

按年份访问数据,您可以使用

For access data by year you can use

db.collection.find({"year":2017});

更新的 PHP 代码:

Updated PHP code:

<?php 
try { 
  $cars = ['Motorolla','Toyota', 'Corolla'] ; 
  $colors = ['blue', 'green', 'black']; 

  $years = [2017, 2016, 2015]; 
  $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); 
  $bulkWriteManager = new MongoDB\Driver\BulkWrite; 

  $query1 =["year" => $years[0]]; 
  $query2 =["year" => $years[1]]; 
  $query3 =["year" => $years[2]]; 

  $update1 = ['$set' => ['car' => $cars[0], 'color' => $colors[0]]]; 
  $update2 = ['$set' => ['car' => $cars[1], 'color' => $colors[1]]]; 
  $update3 = ['$set' => ['car' => $cars[2], 'color' => $colors[2]]]; 

  try { 
    $bulkWriteManager->update($query1, $update1, ["upsert" => true]); 
    $bulkWriteManager->update($query2, $update2, ["upsert" => true]); 
    $bulkWriteManager->update($query3, $update3, ["upsert" => true]); 
     echo 1; 
  } catch(MongoCursorException $e) { 
  /* handle the exception */ 
  echo 0; 
  } 

  $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection 

  } catch (MongoDB\Driver\Exception\Exception $e) { 
    $filename = basename(__FILE__); 
    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n"; 
    echo "Exception:", $e->getMessage(), "\n"; 
  } 
?>

您可以使用聚合管道执行复杂的查询,并且可以添加索引以加快响应速度.

You can perform complex queries using aggregation pipeline and you can add index to make your response quicker.

观察:

第一个解决方案:更新/插入数据更难,但将所有内容放在一起,更容易读取数据.

First Solution : Harder to update/insert data, but keeps everything together so easier to read data.

第二种解决方案:对文档进行 CRUD 操作并使用聚合管道执行复杂查询时更简洁、更简单.

Second Solution : Cleaner and simpler to do CRUD operations on documents and use aggregation pipeline to preform complex queries.

这篇关于使用 PHP 在 Mongo DB 中的文档内添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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