2016-11-04 48 views
0

背景信息如何将信息追加到mongo中的文档中?

我在Mongo的数据库中的以下数据:

{ "_id" : 
     ObjectId("581c97b573df465d63af53ae"), 
     "ph" : "+17771111234", 
     "fax" : false, 
     "city" : "abd", 
     "department" : "", 
     "description" : "a test" 
} 

我现在通过包含我需要追加到数据的CSV文件编写一个脚本,将循环文件。例如,数据可能是这样的:

+17771111234, 10:15, 12:15, [email protected] 
+17771111234, 1:00, 9:00, [email protected] 

最后,我想用一个蒙戈文件看起来像这样结束了:

{ "_id" : 
     ObjectId("581c97b573df465d63af53ae"), 
     "ph" : "+17771111234", 
     "fax" : false, 
     "city" : "abd", 
     "department" : "", 
     "description" : "a test", 
     "contact_locations": [ 
      { 
       "stime": "10:15", 
       "etime": "12:15", 
       "email": "[email protected]" 
      }, 
      { 
       "stime": "1:00", 
       "etime": "9:00", 
       "email": "[email protected]" 
      }, 
     ] 
} 

问题

我的代码实际上写的是创建新文档,而不是附加到现有的文档。实际上,它甚至没有在CSV文件中创建每行新文档...我还没有足够的调试来真正理解原因。

代码

对于CSV文件的每一行,我跑以下逻辑

while(!$csv->eof() && ($row = $csv->fgetcsv()) && $row[0] !== null) { 
    //code that massages the $row into the way I need it to look. 
    $data_to_submit = array('contact_locations' => $row); 
    echo "proving that the record already exists...: <BR>"; 
    $cursor = $contact_collection->find(array('phnum'=>$row[0])); 
    var_dump(iterator_to_array($cursor)); 

    echo "now attempting to update it....<BR>"; 
    // $cursor = $contact_collection->update(array('phnum'=>$row[0]), $data_to_submit, array('upsert'=>true)); 
     $cursor = $contact_collection->insert(array('phnum'=>$row[0]), $data_to_submit); 
    echo "AFTER UPDATE <BR><BR>"; 
    $cursor = $contact_collection->find(array('phnum'=>$row[0])); 
    var_dump(iterator_to_array($cursor)); 
    } 
} 

问题

  1. 有没有办法“追加“文件?或者是否需要抓取现有文档,另存为数组,将我的联系人位置数组与主文档合并,然后重新保存?

  2. 如何查询“contact_locations”对象是否已存在于文档内?

回答

1

嗨,你可以做到这一点!

首先你需要找到自己的文档,并把你所需要的新的价值:

使用findAndModify$addToSet

$cursor = $contact_collection->findAndModify(
    array("ph" => "+17771111234"), 
    array('$addToSet' => 
     array(
      "contact_locations" => array(
       "stime"=> "10:15", 
       "etime"=> "12:15", 
       "email"=> "[email protected]" 
      ) 
     ) 
    ) 
); 

最好的部分是$addToSet不会加2次相同的东西,所以你会没有相同的值的两倍:)

这里的文档https://docs.mongodb.com/manual/reference/operator/update/addToSet/

0

我不确定PHP中的确切语法,因为我从来没有这样做过,但我目前正在用MongoDB在JS中做同样的事情,并且$push是您正在寻找的方法。此外,如果我可能有点挑剔,我建议将$ contact_collection更改为$ contact_locations作为变量名称。数组变量名称通常是复数形式,更具描述性的总是更好。另外,请确保您首先在MongoDB中找到要附加到的数组,并使用MongoDb“更新”命令

相关问题