简体   繁体   中英

php 7 mongodb collection insert

We've installed php mongo ext and then have the composer set up as well.

https://github.com/alcaeus/mongo-php-adapter

In my php code I've this:

require_once 'vendor/autoload.php';

$m = new MongoDB\Client("mongodb://host1,host2",  array ('replicaSet' => 'host-set-01'));
$document = array(....);
$db->mycollection->insert($document);

And it returned this error:

PHP Fatal error: Uncaught Error: Call to undefined method MongoDB\\Collection::insert()

But inside the adapter's folder I do see insert() inside that collection class Mongo/MongoCollection.php

Anyone got it working with the mongodb/adapter?

尝试改用insertOne()insertMany()

This might be help you:

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

    $doc = array(
        'id'      => new MongoDB\BSON\ObjectID,     #Generate MongoID
        'name'    => 'harry',
        'age'     => 14,
        'roll_no' => 1  
    );

    $bulk->insert($doc);
    $mongo->executeBulkWrite('schooldb.student', $bulk);    # 'schooldb' is database and 'student' is collection.

Here By using BulkWriter you can do insert,update and delete operation with one or more than one document.

The client in the library that you link to ( https://github.com/alcaeus/mongo-php-adapter ) is \\MongoClient , not MongoDB\\Client .

The Mongo/MongoCollection.php class is \\MongoCollection , not MongoDB\\Collection as your error suggests.

I think you're trying to use a PHP extension version of Mongo and not the library that you have linked to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM