MongoDB插入

文章目录
[隐藏]

1.MongoDB插入数据

1.1.插入单条数据

db.collection.insertOne({})
> db.logs.insertOne({'date':'2019-06-19','content':'crash'})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5cd0983de8271827134eeb37")
}
> db.logs.find();
{ "_id" : ObjectId("5cd0983de8271827134eeb37"), "date" : "2019-06-19", "content" : "crash" }
> 

1.2.插入多条数据

db.collection.insertMany([{},{},...])
> var insertMany = [{'name':'test','address':'china'},{'name':'test2','address':'china'}]
> db.user.insertMany(insertMany)
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("5cd0aa2ee8271827134eeb38"),
		ObjectId("5cd0aa2ee8271827134eeb39")
	]
}
> db.user.find();
{ "_id" : ObjectId("5cd0aa2ee8271827134eeb38"), "name" : "test", "address" : "china" }
{ "_id" : ObjectId("5cd0aa2ee8271827134eeb39"), "name" : "test2", "address" : "china" }
> 

2.PHP MongoDB插入数据

1. 将数据插入test数据库的test_col集合中
<?php
$m = new MongoClient();    // 连接到mongodb
$db = $m->test;            // 选择一个数据库
$collection = $db->test_col; // 选择集合
$document = array( 
    "title" => "test", 
    "desc" => "this is test"
);
$collection->insert($document);
echo "数据插入成功";
?>

3.PHP7 MongoDB插入数据

1. 将 name 为"test_name" 的数据插入到 test 数据库的 test_col 集合中(集合不存在会创建)
<?php
$bulk = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'test_name'];
$_id= $bulk->insert($document);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.test_col', $bulk, $writeConcern);
?>
221 人浏览过

发表评论

邮箱地址不会被公开。 必填项已用*标注