在MongoDb中插入数组

时间:2015-09-08 16:16:17

标签: php arrays mongodb

我在php中有一个数组,我想在MongoDb中插入它。

假设:

$cars = array("Volvo", "BMW", "Toyota");

我想创建一个文档

{
     {
         "user":user1,
          cars":["volvo","BMW","Toyota"]
     }
}

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

本教程可能会帮助您:http://www.tutorialspoint.com/mongodb/mongodb_php.htm

特别关注本节。

<?php
   // connect to mongodb
   $m = new MongoClient();
   echo "Connection to database successfully";
   // select a database
   $db = $m->mydb;
   echo "Database mydb selected";
   $collection = $db->mycol;
   echo "Collection selected succsessfully";
   $document = array( 
      "title" => "MongoDB", 
      "description" => "database", 
      "likes" => 100,
      "url" => "http://www.tutorialspoint.com/mongodb/",
      "by", "tutorials point"
   );
   $collection->insert($document);
   echo "Document inserted successfully";
?>

所以在你的情况下,你想要像

这样的东西
$document = array(
  'user' => 'user1',
  'cars' => array("Volvo", "BMW", "Toyota"),
);