GithubHelp home page GithubHelp logo

mongodb / mongo-php-library Goto Github PK

View Code? Open in Web Editor NEW
1.6K 72.0 260.0 8.3 MB

The Official MongoDB PHP library

Home Page: https://mongodb.com/docs/php-library/current/

License: Apache License 2.0

PHP 97.01% Shell 0.47% JavaScript 0.37% Python 2.15%
php mongodb mongodb-driver

mongo-php-library's Introduction

MongoDB PHP Library

Tests Coding Standards

This library provides a high-level abstraction around the lower-level PHP driver (mongodb extension).

While the extension provides a limited API for executing commands, queries, and write operations, this library implements a full-featured API similar to that of other MongoDB drivers. It contains abstractions for client, database, and collection objects, and provides methods for CRUD operations and common commands (e.g. index and collection management).

If you are developing an application with MongoDB, you should consider using this library, or another high-level abstraction, instead of the extension alone.

Additional information about the architecture of this library and the mongodb extension may be found in Architecture Overview.

Documentation

Installation

The preferred method of installing this library is with Composer by running the following from your project root:

$ composer require mongodb/mongodb

Additional installation instructions may be found in the library documentation.

Since this library is a high-level abstraction for the driver, it also requires that the mongodb extension be installed:

$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`

Additional installation instructions for the extension may be found in its PHP.net documentation.

Release Integrity

Releases are created automatically and the resulting release tag is signed using the PHP team's GPG key. To verify the tag signature, download the key and import it using gpg:

gpg --import php-driver.asc

Then, in a local clone, verify the signature of a given tag (e.g. 1.19.0):

git show --show-signature 1.19.0

Note

Composer does not support verifying signatures as part of its installation process.

Reporting Issues

Issues pertaining to the library should be reported in the PHPLIB project in MongoDB's JIRA. Extension-related issues should be reported in the PHPC project.

For general questions and support requests, please use one of MongoDB's Technical Support channels.

Security Vulnerabilities

If you've identified a security vulnerability in a driver or any other MongoDB project, please report it according to the instructions in Create a Vulnerability Report.

Development

Development is tracked in the PHPLIB project in MongoDB's JIRA. Documentation for contributing to this project may be found in CONTRIBUTING.md.

mongo-php-library's People

Contributors

alcaeus avatar aleksandr-rudo avatar bjori avatar carusogabriel avatar corpsee avatar dependabot[bot] avatar derickr avatar doublecompile avatar gmsantos avatar gromnan avatar j-licht avatar jdestefano-mongo avatar jmikola avatar kvwalker avatar levon80999 avatar malarzm avatar mlaopane avatar mongodb-php-bot avatar nicolas-grekas avatar norareidy avatar oskarstark avatar petr-buchin avatar remicollet avatar schmalliso avatar serebro avatar smottt avatar tanlisu avatar terakilobyte avatar tuyakhov avatar yosmanyga avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongo-php-library's Issues

[question] Replacement fore MongoCode ?

I'm working on changing an app from old driver to this library with the new PHP driver.

I had some kind of code :

$func = 'db.BlogPost.find().forEach(function(doc){
            db.BlogPost.update(
                {_id:doc._id},
                {$set:{n: NumberLong(db.Comment.find({blogpost:doc._id}).count())}}
            );
        });'

$code = new \MongoCode($func);
$response = $db->execute($code);

I don't find any replacement for this MongoCode() feature is it intended ?

MongoDB\BSON\Date unable to assign date in desired format

Objective is to assign a mongodb ISODate to a php variable. So this is a BSON date object and I am trying to get the date or rather milliseconds property, which I am unable to get.

MongoDB\BSON\UTCDateTime Object ( [milliseconds] => 1455454800000 )

PHP MongoDB Environment:
mongodb version 1.1.0
mongodb stability stable
ibmongoc version 1.1.2
libbson version 1.1.3

MongoDB Pecl Driver php_mongodb-1.1.0-5.6-nts-vc11-x86
mongodb/mongo-php-library 1.0.0
(composer gave exception php_mongodb driver not installed when using the php_mongodb-1.1.0-5.6-nts-vc11-x64 but accepted the php_mongodb-1.1.0-5.6-nts-vc11-x86 )

2016-02-09T22:12:26.428+0000 I CONTROL [initandlisten] db version v3.2.1
2016-02-09T22:12:26.428+0000 I CONTROL [initandlisten] git version: a14d55980c2
cdc565d4704a7e3ad37e4e535c1b2
2016-02-09T22:12:26.429+0000 I CONTROL [initandlisten] OpenSSL version: OpenSSL
1.0.1p-fips 9 Jul 2015
2016-02-09T22:12:26.429+0000 I CONTROL [initandlisten] allocator: tcmalloc
2016-02-09T22:12:26.429+0000 I CONTROL [initandlisten] modules: none
2016-02-09T22:12:26.429+0000 I CONTROL [initandlisten] build environment:
2016-02-09T22:12:26.430+0000 I CONTROL [initandlisten] distmod: 2008plus-ssl
2016-02-09T22:12:26.430+0000 I CONTROL [initandlisten] distarch: x86_64
2016-02-09T22:12:26.430+0000 I CONTROL [initandlisten] target_arch: x86_64

document:

{
        "_id" : ObjectId("56b91366bb782f1d925ef9df"),
        "playerLastName" : "Smith",
        "fixture" : [
                {
                        "opposition" : "Bisons",
                        "date" : ISODate("2016-02-14T13:00:00Z"),
                        "venue" : "Parklands",
                        "available" : 0
                }
        ],
        "playerFirstName" : "John"
} 

php

foreach ($document as $value) {
    $fixtureSel_firstName = $value["playerFirstName"];
    $fixtureSel_lastName = $value["playerLastName"];
    for($i = 0; $i < count($value['fixture']); $i++) {
        $fixtureSel_opposition = $value['fixture'][$i]['opposition'];
        $fixtureSel_date = $value['fixture'][$i]['date'];

        $utcdatetime = new MongoDB\BSON\UTCDateTime($fixtureSel_date);
        $datetime = $utcdatetime->toDateTime();
        var_dump($datetime);

Error
PHP Fatal error: Uncaught exception 'MongoDB\Driver\Exception\InvalidArgumentException' with message 'MongoDB\BSON\UTCDateTime::__construct() expects parameter 1 to be long, object given'

Obviously you can't use the Date object returned, but how do you get the milliseconds and pass that ?

If I pass a string

$date = '1455454800000';

$utcdatetime = new MongoDB\BSON\UTCDateTime($date);
$datetime = $utcdatetime->toDateTime();
$mydate = $datetime->format('Y-m-d H:i:s');
print $mydate;

I get 2016-02-14 13:00:00 which is what I am looking for.

Appreciate any pointers on this.

Issue with Projections

mongodb driver version: 1.1.2
library version: 1.0.0-beta2

Projections don't appear to be having any affect on returned results from findOne or find

Using the following syntax to filter returned values:

$collection->findOne(array("token" => $curr_token),array('desc' => true));

This still returns the entire document for the specified query rather than just the 'desc' field.

The end goal was to use the following filter (which also wasn't having any effect):

array('logs' => array('$elemMatch' => array('read' => false)))

Apologies if this is user error but I have tested multiple filters and none changes the output.

Segmentation fault when specifying username and password

Hi there.

I've noticed that when you specify a username and password in the URI and access control isn't being used, a segmentation fault occurs. Try the following script on a Laravel Homestead VM.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://foo:[email protected]/test');
$server = $manager->selectServer(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY));
$server->executeQuery('db.collection', new MongoDB\Driver\Query([]));
# ~/.homestead/after.sh
# MongoDB
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update
sudo apt-get install mongodb-org pkg-config libsasl2-dev -y

sudo pecl install mongodb

echo 'extension=mongodb.so' | sudo tee /etc/php5/mods-available/mongodb.ini
sudo ln -s /etc/php5/mods-available/mongodb.ini /etc/php5/fpm/conf.d/mongodb.ini
sudo ln -s /etc/php5/mods-available/mongodb.ini /etc/php5/cli/conf.d/mongodb.ini

sudo service php5-fpm restart

Not critical but it threw one of the unit tests I was using.

php: symbol lookup error: /usr/lib/php/20151012/mongodb.so: undefined symbol: _mongoc_host_list_destroy_all

I dont know if this is the right place to put it but I have a problem. In my case Im using Lumen 5.2, PHP 7.0.2 - MongoDB 1.1.2 - Ubuntu 14.04... etc.

On my composer.json file

"illuminate/redis":"5.2.*",
"predis/predis": "^1.1@dev"

When i run my unit tests it results in this error:

.2016/02/03 15:35:03.0458: [ 1359]:    DEBUG:       client: Using custom stream initiator.
php: symbol lookup error: /usr/lib/php/20151012/mongodb.so: undefined symbol: _mongoc_host_list_destroy_all

The only reference on google whas this file: https://github.com/mongodb/mongo-c-driver/blob/master/src/mongoc/mongoc-uri.c

When I install everything in the server I use the ondrej/phprepository. You can look-up the setup installation script here: https://github.com/jonathanpmartins/ubuntusetup/blob/master/server/setup-php7-nginx-1.9.10-ubuntu-14.04.sh

Perhaps I should open a issue on another repository. Can someone help me out?

Upsert option not working

I have implemented this new library and the save function is deprecated. I wan't to use the insertOne with the upsert option, but it fails.

$this->_connection = new MongoDB\Client($host);
$this->_db = $this->_connection->{$this->_database};

$this->_collection = $this->_db->{$this->_table};
$this->_collection->createIndex(array("_id" => 1));

$result = $this->_collection->insertOne(array("_id" => $this->key($id, $group), "group" => $group, "data" => $data, "timeStamp" => time() + $this->options['lifetime']), ['upsert' => true]);

This will return a BulkWrite error with code 0 and no message.
What is wrong with the code?

There isn't any TODO list nor anything similar to help new contributors knowing where to start

Hi,

there isn't any TODO list nor anything similar (like using this 'bugtracker' with specific tags) to help new contributors knowing where to start or which features aren't developed yet.

I'll try to help if there are a comprehensible TODO list, but I haven't the time to explore the entire mongo PHP prototypes source code because business is business. First user stories, (sadly for me) in last place the portability and my dreamed port to HHVM.

findOne return is not array

<?php

// This path should point to Composer's autoloader
require_once __DIR__ . "/vendor/autoload.php";

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "db.abc");
$sunnyvale = $collection->findOne(array("id" => 94086));
var_dump($sunnyvale);

?>

output is object.

object(stdClass)#18 (22) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectID)#12 (1) {
    ["oid"]=>
    string(24) "56820bdc10167adb058b4567"
  }
  ["id"]=>
  int(94086)
  ...
}

$collection->find(); bson error, new Query() fails

Collection.php
Line: 1139: $query = new Query($filter, $options); silently fails.

For now just to get working: i replaced this line with: $query = new Query($filter);

I'll try to find a write way to fix this and will update the information.

Composer won't return any namespaces for this package

I tried running composer to install this package for a project. When I go to load a class like...

$bulk = new MongoDB\Driver\BulkWrite;

I says it can't find the class. Upon looking further I see there is no namespaces returned in the composer autoload file. Like this...

<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
);

It's a clean project, am I doing something wrong?

Thanks,
Stefan

Call to undefined function MongoDB\server_supports_feature

Call to undefined function MongoDB\server_supports_feature() in /var/www/localhost/composer/mongodb/mongodb/src/Collection.php on line 527

Call to undefined function MongoDB\is_first_key_operator() in /var/www/localhost/composer/mongodb/mongodb/src/Operation/FindOneAndUpdate.php on line 68

PHP 5.6.16-2+deb.sury.org~precise+1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
    with Xdebug v2.3.3, Copyright (c) 2002-2015, by Derick Rethans

mongodb

mongodb support => enabled
mongodb version => 1.1.2
mongodb stability => stable
libmongoc version => 1.3.1-dev
libbson version => 1.3.0

Directive => Local Value => Master Value
mongodb.debug => no value => no value

Easier way to return array as default

I'm trying to use this library in a project who uses the old driver.
But now the default behavior is to return objects from queries.
The only way I found was to make a wrapper around Collection and to specify for each operation (find, findOne, aggregate...) the type map.
Is there a better way to do this? Do you plan having default options for this kind of use case? (inherit from database/client, similar to read preference)
Thanks!

[Question] Guide to contributing?

Is MongoDB looking for 3rd-party contributions to this code, or is it intended for primarily internal development? With the library going 1.0 stable, and this class going 1.0 beta, will things like code styling and documentation be areas to contribute to?

Cannot access protected property ::$_id

I have document with protected $_id; and function getId() but the error show in Operation/InsertOne.php in line 83:

$insertedId = is_array($this->document) ? $this->document['_id'] : $this->document->_id;

When I remove that line, document is inserted with new id without problems.

PHP 7.0.1, mongodb v2.6.11, mongodb driver 1.1.1.
.

"No data received error" when calling findOne method

I have a strange issue with findOne method. When I call it I get this No data received ERR_EMPTY_RESPONSE error in chrome. find method works fine!

This is what I found in apache error logs:

/private/tmp/pear/install/mongodb/src/libmongoc/src/mongoc/mongoc-cursor.c:52 _mongoc_n_return(): precondition failed: remaining > 0
[Mon Dec 21 00:08:58.512815 2015] [core:notice] [pid 11959] AH00052: child pid 15139 exit signal Abort trap (6)
/private/tmp/pear/install/mongodb/src/libmongoc/src/mongoc/mongoc-cursor.c:52 _mongoc_n_return(): precondition failed: remaining > 0
[Mon Dec 21 00:08:59.512918 2015] [core:notice] [pid 11959] AH00052: child pid 15323 exit signal Abort trap (6)
/private/tmp/pear/install/mongodb/src/libmongoc/src/mongoc/mongoc-cursor.c:52 _mongoc_n_return(): precondition failed: remaining > 0
[Mon Dec 21 00:09:30.388006 2015] [core:notice] [pid 11959] AH00052: child pid 15325 exit signal Abort trap (6)

deleteMany not working with $in filter

Am I doing something wrong here or this is a bug?

/** @var Collection $collection */
$collection->deleteMany(['_id' => ['$in', [1, 2, 3, 4, 5]]]);

So, I can see documents with _id's 1, 2, 3, 4, 5 in my MongoDB, but they are not deleted by this command.

Argument 1 passed to MongoDB\Driver\BulkWrite::__construct() must be of the type array

Hey guys,

I'm using mongo-phplibrary with mongodb driver, and trying to insertOne document to tests.

But I'm receiving that error:
PHP Catchable fatal error: Argument 1 passed to MongoDB\Driver\BulkWrite::__construct() must be of the type array, boolean given, in C:\...\vendor\mongodb\mongodb\src\Collection.php on line 1024

I change that code:

public function insertOne($document)
{
        $options = array_merge($this->getWriteOptions());

        $bulk = new BulkWrite($options["ordered"]);

To this, and worked:

public function insertOne($document)
{
        $options = array_merge($this->getWriteOptions());

        $bulk = new BulkWrite($options);

So, is that a bug?

Edit: I'm using version 1.0.0 of mongodb driver

RuntimeException without message when sleeping >= 1s

Thing version
MongoDB server v2.4.9
mongodb extension 1.0.0
mongodb/mongodb 1.0.0-beta1

Maybe I'm doing something wrong, but this case came up in a unit test:

<?php
require __DIR__ . '/vendor/autoload.php';

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$collection = new MongoDB\Collection($manager, 'imbo.image');

$result = $collection->findOne(['user' => 'pub']);
sleep(1);
$result = $collection->findOne(['user' => 'pub']);

Result:

PHP Fatal error:  Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' in /home/espenh/webdev/imbo2/vendor/mongodb/mongodb/src/Operation/Find.php:165
Stack trace:
#0 /home/espenh/webdev/imbo2/vendor/mongodb/mongodb/src/Operation/Find.php(165): MongoDB\Driver\Server->executeQuery('imbo.image', Object(MongoDB\Driver\Query), Object(MongoDB\Driver\ReadPreference))
#1 /home/espenh/webdev/imbo2/vendor/mongodb/mongodb/src/Operation/FindOne.php(80): MongoDB\Operation\Find->execute(Object(MongoDB\Driver\Server))
#2 /home/espenh/webdev/imbo2/vendor/mongodb/mongodb/src/Collection.php(346): MongoDB\Operation\FindOne->execute(Object(MongoDB\Driver\Server))
#3 /home/espenh/webdev/imbo2/test.php(15): MongoDB\Collection->findOne(Array)
#4 {main}
  thrown in /home/espenh/webdev/imbo2/vendor/mongodb/mongodb/src/Operation/Find.php on line 165

I tried to wrap the code in a try/catch, the result from $e->getMessage() is a blank string.

I also tried to set a whole bunch of timeouts I could find:

[
    'waitQueueTimeoutMS' => 2000,
    'connectTimeoutMS' => 2000,
    'socketTimeoutMS' => 2000,
    'maxIdleTimeMS' => 2000,
    'wtimeoutMS' => 2000,
]

But none of these seemed to make any difference.

Any suggestions?

Aggregate: FieldPath field names may not start with '$'.

I got the error when I passed the $filter array into the aggregateDocumentsByFilter function. However, I didn't get error when I declared the $filter inside of the aggregateDocumentsByFilter function. (It might be the '$' issue)

** $filter = [
['$match' => ['Id' => ['$eq' => $id]]],
];

// Error
public function aggregateDocumentsByFilter($collection, $filter)
{
$cursor = $collection->aggregate($filter);

    return $cursor;

}

// No Error
public function aggregateDocumentsByFilter($collection, $id)
{
$filter = [
['$match' => ['Id' => ['$eq' => $id]]],
];

    $cursor = $collection->aggregate($filter);

    return $cursor;

}**

Segmentation fault 11 using $driverOptions in Manager::__construct

I am trying to do this:

            $context = stream_context_create(['ssl' => [
                'allow_self_signed' => true,
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'verify_expiry'     => false]
            ]);

            $manager = new Manager('mongodb://127.0.0.1:27017', ['ssl' => true], ['context' => $context]);

            $collection = new Collection($manager, 'dbName.collectionName');

            $data = $collection->findOneAndUpdate(
                ['timestamp' => ['$lt' => time() - 60]],
                ['$set' => ['in_process' => true]],
                ['sort' => ['timestamp' => 1]]
            );

but I get "Segmentation fault: 11". The actual crash is at Collection.php:525

$server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

OSX El Capitan
Homebrew PHP 5.6.16
Homebrew mongodb 1.1.1
PHP library 1.0.0-beta2

Am I doing something wrong or is this maybe Homebrew specific? I haven't tried the PECL library directly.

fatal error when save ObjectID to php session

I save some user base info with the CI's session driver, like userid, company_id... in an array.
All of these named xxx_id in the array are MongoDB's ObjectID, but when i save these data to session i got this error.

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'MongoDB\BSON\ObjectID' is not allowed' in [no active file]:0 Stack trace: #0 [internal function]: session_write_close() #1 {main} thrown in [no active file] on line 0.

But, when using mongodb legacy driver for php, all things fine.
I don't know how to solve it.

readConcern.level Error

I'm trying to move from mongofill to this library. I've successfully build and added HHVM driver but keep getting this error.

Fatal error: Uncaught exception 'MongoDB\\Driver\\Exception\\RuntimeException' with message 'readConcern.level must be either 'local' or 'majority'' in /site/External/mongo-php-library/src/Operation/Find.php:179
Stack trace:
#0 /site/External/mongo-php-library/src/Operation/Find.php(179): MongoDB\\Driver\\Server->executeQuery()
#1 /site/External/mongo-php-library/src/Collection.php(439): MongoDB\\Operation\\Find->execute()
#2 /site/Service/Main.hh(7): MongoDB\\Collection->find()
#3 /site/Core/Main.hh(18): Service_Main::Packages()
#4 /site/Main.hh(18): Core_Main::initialize()
#5 {main}

I'm not sure how to set default readConcern.level. Any help would be appreciated.

Program terminated with signal SIGSEGV, Segmentation fault

backtrace

gdb /usr/local/php7/sbin/php-fpm /tmp/coredump-php-fpm.25892
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /usr/local/php7/sbin/php-fpm...done.
[New LWP 25892]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `php-fpm: pool www                                                             '.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  mongoc_set_id_cmp (a_=a_@entry=0x7ffefef4a690, b_=b_@entry=0xc5731b5e333e4900) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-set.c:49
49     if (a->id == b->id) {
(gdb) bt
#0  mongoc_set_id_cmp (a_=a_@entry=0x7ffefef4a690, b_=b_@entry=0xc5731b5e333e4900) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-set.c:49
#1  0x00007f46d2713d6c in bsearch (__compar=0x7f46d2713b20 <mongoc_set_id_cmp>, __size=16, __nmemb=<optimized out>, __base=0x7f46d30af0a0, __key=0x7ffefef4a690) at /usr/include/x86_64-linux-gnu/bits/stdlib-bsearch.h:33
#2  mongoc_set_get (set=<optimized out>, id=id@entry=1) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-set.c:114
#3  0x00007f46d271c79b in mongoc_topology_description_server_by_id (description=description@entry=0x7f46d305f940, id=id@entry=1, error=error@entry=0x0) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-topology-description.c:535
#4  0x00007f46d271a9ed in mongoc_topology_server_by_id (topology=0x7f46d305f940, id=id@entry=1, error=error@entry=0x0) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-topology.c:571
#5  0x00007f46d26fde14 in mongoc_cluster_stream_for_server (cluster=cluster@entry=0x7f46d30600d8, server_id=server_id@entry=1, reconnect_ok=reconnect_ok@entry=false, error=error@entry=0x0) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-cluster.c:1407
#6  0x00007f46d26f9f8d in _mongoc_client_kill_cursor (client=0x7f46d30600c0, server_id=1, cursor_id=85316428959, db=db@entry=0x7ffefef4a940 "fitTime", collection=0x7f46d30a2348 "picList") at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-client.c:1273
#7  0x00007f46d2703db8 in _mongoc_cursor_destroy (cursor=0x7f46d30a2200) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-cursor.c:271
#8  0x00007f46d2703e8d in mongoc_cursor_destroy (cursor=0x7f46d30a2200) at /root/soft/mongodb-1.1.1/src/libmongoc/src/mongoc/mongoc-cursor.c:247
#9  0x00007f46d272d561 in php_phongo_cursor_free (cursor=0x7f46d3067b40) at /root/soft/mongodb-1.1.1/php_phongo.c:2073
#10 0x0000000000818741 in zend_objects_store_del (object=0x7f46d3067ba8) at /root/soft/php-src-php-7.0.1/Zend/zend_objects_API.c:182
#11 0x00000000007df126 in _zval_dtor_func_for_ptr (p=<optimized out>) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.c:109
#12 0x00000000007f0c07 in i_zval_ptr_dtor (zval_ptr=0x7f46d3061760) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.h:58
#13 zend_array_destroy (ht=0x7f46d308d0e0) at /root/soft/php-src-php-7.0.1/Zend/zend_hash.c:1301
#14 0x00000000007df116 in _zval_dtor_func_for_ptr (p=<optimized out>) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.c:96
#15 0x0000000000813dfc in i_zval_ptr_dtor (zval_ptr=0x7f46d3073108) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.h:58
#16 zend_object_std_dtor (object=0x7f46d30730e0) at /root/soft/php-src-php-7.0.1/Zend/zend_objects.c:69
#17 0x0000000000818741 in zend_objects_store_del (object=0x7f46d30730e0) at /root/soft/php-src-php-7.0.1/Zend/zend_objects_API.c:182
#18 0x00000000007df126 in _zval_dtor_func_for_ptr (p=<optimized out>) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.c:109
#19 0x0000000000813dfc in i_zval_ptr_dtor (zval_ptr=0x7f46d30751f8) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.h:58
#20 zend_object_std_dtor (object=0x7f46d30751c0) at /root/soft/php-src-php-7.0.1/Zend/zend_objects.c:69
#21 0x0000000000818741 in zend_objects_store_del (object=0x7f46d30751c0) at /root/soft/php-src-php-7.0.1/Zend/zend_objects_API.c:182
#22 0x00000000007df126 in _zval_dtor_func_for_ptr (p=<optimized out>) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.c:109
#23 0x00000000007d5aa4 in i_zval_ptr_dtor (zval_ptr=0x7f46d3068020) at /root/soft/php-src-php-7.0.1/Zend/zend_variables.h:58
#24 zend_cleanup_internal_class_data (ce=<optimized out>) at /root/soft/php-src-php-7.0.1/Zend/zend_opcode.c:188
#25 0x00000000007e6dc9 in zend_cleanup_internal_classes () at /root/soft/php-src-php-7.0.1/Zend/zend_API.c:2585
#26 0x00000000007d1eea in shutdown_executor () at /root/soft/php-src-php-7.0.1/Zend/zend_execute_API.c:338
#27 0x00000000007e09c7 in zend_deactivate () at /root/soft/php-src-php-7.0.1/Zend/zend.c:967
#28 0x0000000000783c01 in php_request_shutdown (dummy=dummy@entry=0x0) at /root/soft/php-src-php-7.0.1/main/main.c:1810
#29 0x00000000004400d6 in main (argc=<optimized out>, argv=<optimized out>) at /root/soft/php-src-php-7.0.1/sapi/fpm/fpm/fpm_main.c:1972

Force arrays as arrays instead of bsonArray?

Hi!
I'm using array_merge to merge multiple arrays from a bunch of documents. Used to work but not anymore since by default, arrays are now bsonarrays. Is there a way, when using find or findOne to get the arrays inside a document treated as arrays? I'm trying to avoid using my_bson_array->bsonSerialize(); to convert it since this occurs at many places in my soft.
Thank you

This is an issue...

What advantages are there to this new driver? More importantly what was wrong with the old one? Moving forward this will cost thousands of companies including ours a great deal of time and effort to re-implement everything.

It feels there has been little explanation here for the change and feels more like a "because we can" situation.

When should this be upgraded? Is it now considered stable? When will support be lost for the old driver?

distinct behavior differs from db?

From mongo docs:
db.collection.distinct()
Returns an array of documents that have distinct values for the specified field.

PHP Lib doc:
Finds the distinct values for a specified field across the collection.
I tested and it returns the distinct values of the specified field instead of the documents associated.

How to obtain db behavior instead?

Losing metadata when updating an object implementing Persistable

Hello,

I'm having trouble updating one document that implements the Persistable interface.
It's unserialization metadata get lost every time I replace the document.

Here's an exemple showing the problem:

<?php

require 'vendor/autoload.php';

class A implements \MongoDB\BSON\Persistable
{
    private $name;
    public function __construct($name)
    {
        $this->name = $name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function bsonSerialize()
    {
        return [
            'name' => $this->name
        ];
    }

    public function bsonUnserialize(array $data)
    {
        $this->name = $data['name'];
    }
}

$instance = new A('foo');

$manager = new \MongoDB\Driver\Manager('mongodb://mongo:27017');
$collection = new \MongoDB\Collection($manager, 'test', 'coll');
$result = $collection->insertOne($instance);

/**
 * > db.coll.find()
 * {
 *         "_id" : ObjectId("56a269e0046d5f0014645471"),
 *         "__pclass" : BinData(128,"QQ=="),
 *         "name" : "foo"
 * }
 */

$instance->setName('bar');
$collection->replaceOne(['_id' => $result->getInsertedId()], $instance);

/**
 * > db.coll.find()
 * { "_id" : ObjectId("56a26a97046d5f0039107a21"), "name" : "bar" }
 */

What am I doing wrong here please?

I'm running mongodb server v3.2.1.

Thanks in advance!

Compatibility layer for old code

Hi there,

I had a quick look around but couldn't find a compat layer on top of the new API to simulate the old extension. If there is any I'd be keen to learn about that.

In the meantime I started my own :https://github.com/DerManoMann/mongodb-bc :)

I've got a large project with lots of other issues around upgrading to PHP7, so having something that makes the existing (legacy) MongoDB code work is a big help.

Cheers, mano

undefined method MongoDB\Driver\Manager::executeInsert() (test suite)

Trying to run the test suite:

Fatal error: Call to undefined method MongoDB\Driver\Manager::executeInsert() in /tmp/mongo-php-library/tests/ClientFunctionalTest.php on line 27

There is a mongodb server v 2.4.14 running and listening to port 27017

In debug:

 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Connection string: 'mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100'
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Creating Manager, phongo-1.0.0[stable] - mongoc-1.2.0(1.2.0), libbson-1.2.0(1.2.0), php-5.6.15
 [2015-10-31T07:40:32+00:00]     client: DEBUG   > Using custom stream initiator.
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Connection string: 'mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100'
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Creating Manager, phongo-1.0.0[stable] - mongoc-1.2.0(1.2.0), libbson-1.2.0(1.2.0), php-5.6.15
 [2015-10-31T07:40:32+00:00]     client: DEBUG   > Using custom stream initiator.
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Connecting to '127.0.0.1:27017[mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100]'
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Created: RSRC#142 as '127.0.0.1:27017[mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100]'
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 0
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 0
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Reading got: 4 wanted: 0
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 0
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Reading got: 127 wanted: 0
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 300000
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 300000
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Reading got: 4 wanted: 4
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Setting timeout to: 300000
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Reading got: 74 wanted: 74
 [2015-10-31T07:40:32+00:00]     PHONGO: DEBUG   > Not destroying RSRC#-1

ReadPreference and slaveOk

While setting read preference on a secondary, i get this error: not master and slaveOk=false.
But I can't find how to set it with the driver.
Thanks!

findOne fails

PECL 1.1.1 + lib 1.0.0@beta
$collection->findOne(['name' => 'john']);
ext\mongodb\src\libmongoc\src\mongoc\mongoc-cursor.c:52 _mongoc_n_return(): precondition failed: remaining > 0

$collection->find(['name' => 'john']);
//works

updateOne with objectid?

Seems like there is noway to update a document based on its objectId.

hard-coded example:

$collection->updateOne(['_id' => '567eba6ea0b67b21dc004687'], ['$set' => ['some_property' => 'some_value']]);

Won't update. How to update by id?

We need some better documentation please

This is not a bug in the code (I hope) but is a problem with the documentation.
I find how to get collections and then do a var_dump, but I can't find any place that helps me to get some field on that object.
I have tried every single way to do this, and it seems that find or findOne doesn't work. Documentation is not good enough and that's very bad for MongoDB, we just can't advance in our projects.

I have this document

{ 
    "_id" : ObjectId("56a22142bd1457041e2c94b2"), 
    "anonymousId" : "7f668198-e985-426e-9232-084c440f7293", 
    "channel" : "client", 
    "context" : {
        "ip" : "1.175.1.14", 
        "library" : {
            "name" : "analytics.js", 
            "version" : "2.11.1"
        }, 
        "page" : {
            "path" : "/", 
            "referrer" : "http://www.google.com/", 
            "search" : "", 
            "title" : "Title", 
            "url" : "http://www.google.com"
        }, 
        "userAgent" : "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0"
    }, 
    "integrations" : {

    }, 
    "messageId" : "ajs-492650bab68cd4305f8a56a769299ea6", 
    "originalTimestamp" : "2016-01-22T12:32:10.657Z", 
    "projectId" : "V7vqDI8qKo", 
    "receivedAt" : "2016-01-22T12:32:01.832Z", 
    "sentAt" : "2016-01-22T12:32:10.657Z", 
    "timestamp" : "2016-01-22T12:32:01.832Z", 
    "type" : "identify", 
    "userId" : "[email protected]", 
    "version" : NumberInt(2)
}

Can somebody tell me how to get userId from that document in PHP?
Also I have noticed that find and findOne returns different objects, different data.
Can somebody tell me how to get userId from one result and from a collection in a foreach?

This is a silly question, but I can't find any documentation that says that. All the examples are for the old driver (mongo, not mongodb), but not for this.
Thank you

MongoClient vs MongoDB backward compatibility issues

Hello.

I tried migrate from MongoClient to MongoDB and that was quite hard. Issues I'll found:

  1. MongoDB\Collection has no method to set read preference, we cant use constructor instead because of our private factory. Old MongoClient had setReadPreference, can you return it?
  2. MongoDB\Collection has no "limit" method like old MongoClient does, can you return it?
  3. findOne(['_id' => $id]) call returns item without "_id" property, it is empty (null). Can you fix it?

Can't insert data into collection

Hi Team, i found an issue with insert data into collection both using insertOne() and insertMany(), but i can make it works if i change this line $bulk = new BulkWrite($options["ordered"]); to $bulk = new BulkWrite(); on Collection.php:1024

the error message was like this

\BulkWrite::__construct() must be of the type array, boolean given in /var/www/myapp/vendor/mongodb/mongodb/src/Collection.php:1024

i think it comes from this block Collection:973-980

public function getWriteOptions()
    {
        return array(
            "ordered" => false,
            "upsert"  => false,
            "limit"   => 1,
        );
    }

default value of ordered is false but \BulkWrite::__construct() expect an array or null instead false.

sorry if i'm wrong here, i'm newbie :), but i just follow a simple tutorial but it doesn't work because this issue. and sorry if my english not good. thanks

updateOne update property with same value doesn't return nModified = 1

Hi!
I'm using
$collection->updateOne($query, ['$set' => [$prop => $value]]);
While using $set with updateOne, if the value is different than the one currently set for the document, it will return nMatched = 1, nModified = 1. If the value is the same, it will return nMatched = 1 and nModified = 0. I understand why, since it didn't update with the same value. But from a user stand point, I still need to be able to return that the document has been modified to avoid checking if the user is trying to update with the same value (which has no incidence). So question, is there a way to have the driver returning nModified = 1 even if the value was the same?

Extending the library

Hello
Thx for creating library for PHP7
I wanted to use this library but I can't find the way to extend it. Looks like it doesn't suppose to be extended. What if I want to use custom Collection class with custom methods? I can't extend it cause all properties are private. Should I fork it and customise for myself? Should I use it as it is? Maybe you can give me some ideas how to wrap it? Thx in advance.

configure: error: Cannot find OpenSSL's


[jose@localhost ~]$ sudo pecl install mongodb
[sudo] password for jose: 
downloading mongodb-1.1.2.tgz ...
Starting to download mongodb-1.1.2.tgz (642,582 bytes)
.....................done: 642,582 bytes
349 source files, building
running: phpize
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525
building in /var/tmp/pear-build-root6aljUg/mongodb-1.1.2
running: /var/tmp/mongodb/configure
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib
checking for PHP extension directory... /usr/lib64/php/modules
checking for PHP installed headers prefix... /usr/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... no
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... gawk
checking whether to enable mongodb support... yes, shared
checking OpenSSL dir for mongodb... yes
checking PHP version... 50416
checking whether to enable developer build flags... no
checking whether to enable code coverage... no
checking whether to use system libbson... no
checking configuring libmongoc... ...
checking whether to use system libmongoc... no
checking for pkg-config... /usr/bin/pkg-config
configure: error: Cannot find OpenSSL's <evp.h>
ERROR: /var/tmp/mongodb/configure' failed

Hey guys i need help with installing the php libraries. when i ran the pecl comand the terminal brought out this:

configure: error: Cannot find OpenSSL's <evp.h>
ERROR: /var/tmp/mongodb/configure' failed

when i opened /var/tmp/ i couldn't even find the mongodb folder. what should i do.
if the formationg is wrong sorry mate im new here.

composer issue

I am testing my app on both php 7 and hhvm.

I have successfully installed the relevant mongodb.so extension.
composer require "mongodb/mongodb=^1.0.0@beta"
I noticed that when I use php 7 to run composer update, it installs mongodb/mongodb (1.0.0-beta2).
The same code running MongoDB then works on php 7 BUT does not work on HHVM:

error: Fatal error: Call to undefined method MongoDB\\Driver\\Manager::getReadConcern() in /home/vagrant/Code/ICO2/vendor/mongodb/mongodb/src/Collection.php on line 105

When I use hhvm to run composer update, it removes 1.0.0-beta2 and installs 1.0.0-beta1.
The same code then WORKS on php 7 and hhvm.

What is going on? Is there are breaking change in the beta2 library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.