Basic MongoDB operations using PHP

Source: Internet
Author: User
Tags findone

Speaking of PHP connected to MongoDB, have to first introduce the official PHP manual, URL in: http://us.php.net/manual/en/book.mongo.php

In PHP's Mongo extension, four types of interfaces (objects) are provided ):

1. MongoDB connection operations: Mongo

Http://us.php.net/manual/en/class.mongo.php

2. Operations on MongoDB databases: MongoDB

Http://us.php.net/manual/en/class.mongodb.php

3. collection operations in MongoDB: collections collection

Http://us.php.net/manual/en/class.mongocollection.php

4. query result set operation: Export cursor

Http://us.php.net/manual/en/class.mongocursor.php

Establish a connection with MongoDB:

Directly instantiate the Mongo class + create a connection:

$ Mo = new Mongo (); // get a mongo connection object

A Mongo class is instantiated and connected to the default localhost: 27017 port MongoDB.

If you want to connect to another host, you can write as follows:$ Mongo = new Mongo ("MongoDB: // username: password@192.168.1.22: 12345 ");


Another way to instantiate the Mongo class, then manually establish the connection :( http://www.my400800.cn
)

$ Mongo = new Mongo ("MongoDB: // username: password@192.168.1.22: 12345", array ('connect' => false); // initialize the class

$ Mongo-> connect (); // create a connection

Some useful methods in the Mongo class:

Mongo: listdbs ()

Http://us.php.net/manual/en/mongo.listdbs.php

Returns an array containing the database information of the current Mongo service.

$ Mo = new Mongo ();

$ DBS = $ Mo-> listdbs (); // obtain an array containing dB Information

Mongo: selectcollection ($ db, $ Coll)

Http://us.php.net/manual/en/mongo.selectcollection.php

Returns a collection object in a DB of the current connection.

$ Mo = new Mongo ();

$ Coll = $ Mo-> selectcollection ('db', 'mycoll '); // get a collection object

 

Select the desired database (Mongo class ):


One method:

Http://us.php.net/manual/en/mongo.get.php

$ Mongo = new Mongo ();

$ Db = $ mongo-> Foo; // get a MongoDB object

Another method:

Http://us.php.net/manual/en/mongo.selectdb.php

$ Mongo = new Mongo ();

$ Db = $ mongo-> selectdb ('foo'); // get a MongoDB object

Useful functions in MongoDB:

Create a MongoDB object

Http://us.php.net/manual/en/mongodb.construct.php

$ Mo = new Mongo ();

$ Db = new MongoDB ($ Mo, 'dbname'); // obtain a MongoDB object through creation

Delete current DB

Http://us.php.net/manual/en/mongodb.drop.php

$ Db = $ Mo-> dbname;

$ Db-> drop ();

Obtain the current database name

Http://us.php.net/manual/en/mongodb.-tostring.php

$ Db = $ Mo-> dbname;

$ Db-> _ tostring ();

Select the desired collection:

A:

$ Mo = new Mongo ();

$ Coll = $ Mo-> dbname-> collname; // get a collection object

B:

$ Db = $ Mo-> selectdb ('dbname ');

$ Coll = $ db-> collname;

C:

$ Db = $ Mo-> dbname;

$ Coll = $ db-> selectcollectoin ('collname'); // get a collection object

Insert data (Collection object ):


Http://us.php.net/manual/en/mongocollection.insert.php

Collections collection: insert (array $ A, array $ options)


Array $ A the array to be inserted

Array $ options






Whether safe returns operation result information

Whether fsync is directly inserted to the physical hard disk

Routine:

$ Coll = $ Mo-> DB-> Foo;

$ A = array ('A' => 'B ');

$ Options = array ('safe '=> true );

$ Rs = $ Coll-> insert ($ A, $ options );

$ RS is an array containing operation information.

Delete a record (Collection object) in the database ):


Http://us.php.net/manual/en/mongocollection.remove.php

Collections collection: Remove (array $ criteria, array $ options)

Array $ criteria Condition

Array $ options

Whether safe returns operation results

Whether fsync directly affects the physical hard disk

Does justone affect only one record?

Routine:

$ Coll = $ Mo-> DB-> Coll;

$ C = array ('A' => 1, 's' => array ('$ lt' => 100 ));

$ Options = array ('safe '=> true );

$ Rs = $ Coll-> remove ($ C, $ options );

$ RS is an array containing operation information.

Update a record (Collection object) in the database ):


Http://us.php.net/manual/en/mongocollection.update.php

Collections collection: Update (array $ criceria, array $ newobj, array $ options)

Array $ criteria Condition

Array $ newobj content to be updated

Array $ options

Whether safe returns operation results

Whether fsync directly affects the physical hard disk

Add a new

MultipleWhether all matching records are affected. By default, only one record is affected.

Routine:

$ Coll = $ Mo-> DB-> Coll;

$ C = array ('A' => 1, 's' => array ('$ lt' => 100 ));

$ Newobj = array ('E' => 'F', 'x' => 'y ');

$ Options = array ('safe '=> true, 'Multiple' => true );

$ Rs = $ Coll-> remove ($ C, $ newobj, $ options );

$ RS is an array containing operation information.

Query collection to obtain a single record (collections collection class ):


Http://us.php.net/manual/en/mongocollection.findone.php

ArrayCollections collection: findone (array $ query, array $ fields)

Array $ query Condition

Array $ fields field to be obtained

Routine:

$ Coll = $ Mo-> DB-> Coll;

$ Query = array ('s '=> array (' $ lt '=> 100 ));

$ Fields = array ('A' => true, 'B' => true );

$ Rs = $ Coll-> findone ($ query, $ fields );

If there is a result, an array is returned. If there is no result, null is returned.

Query collection to obtain multiple records (collections collection class ):

Http://us.php.net/manual/en/mongocollection.find.php

MongocursorCollections collection: FInd (array $ query, array $ fields)

Array $ query Condition

Array $ fields field to be obtained

Routine:

$ Coll = $ Mo-> DB-> Coll;

$ Query = array ('s '=> array (' $ lt '=> 100 ));

$ Fields = array ('A' => true, 'B' => true );

$ Cursor = $ Coll-> Find ($ query, $ fields );

Returns a cursor.

The cursor operation on the cursor object (cursor class ):

Http://us.php.net/manual/en/class.mongocursor.php

Loop or result record:

$ Cursor = $ Coll-> Find ($ query, $ fields );

While ($ cursor-> hasnext ()){

$ R = $ cursor-> getnext ();

Var_dump ($ R );

}

Or

$ Cursor = $ Coll-> Find ($ query, $ fields );

Foreache ($ cursor as $ k => $ v ){

Var_dump ($ V );

}

Or

$ Cursor = $ Coll-> Find ($ query, $ fields );

$ Array = iterator_to_array ($ cursor );

A blood lesson:

Http://us.php.net/manual/en/mongocursor.snapshot.php

 

 

In
We performed the find () operation. After obtaining the $ cursor, the cursor is still dynamic, that is
When I obtain the cursor and complete the corresponding record in my loop operation, the result set is automatically added if the number of matching records is increased by default. In other words, after I find (),
When the cursor loop is completed, if any matching record is inserted to the collection, the records will also be obtained by $ cursor.

If you want to keep the result set unchanged after obtaining $ cursor, you need to do the following:

$ Cursor = $ Coll-> Find ($ query, $ fields );

$ Cursor-> snapshot ();

Foreache ($ cursor as $ k => $ v ){

Var_dump ($ V );

}




Next let's use the group operation and group by group_id to calculate the count:

<? PHP

Ini_set ('mongo. native_long ', 1 );

$ Instance = new Mongo ();

$ Instance = $ instance-> selectcollection ('test', 'test ');

$ Keys = array ('group _ id' => 1 );

$ Initial = array ('Count' => 0 );

$ Reduce ='
Function (OBJ, Prev ){
Prev. Count + = obj. count;
}
';

$ Result = $ instance-> group ($ keys, $ initial, $ reduce );

Var_dump ($ result );

?>

The result is different from the Expected One. The count is not accumulated, but is changed to [object]. Currently, If you must use the group operation, there are two ways to alleviate this problem:

Ini_set ('mongo. native_long ', 0 );

$ Initial = array ('Count' => (float) 0 );

Both of these methods are temporary and temporary remedies. Since the Group implementation in the PHP driver is faulty, we can bypass it and implement the same function in other ways. This approach isMapreduce:

<? PHP

Ini_set ('mongo. native_long ', 1 );

$ Instance = new Mongo ();

$ Instance = $ instance-> selectdb ('test ');

$ Map ='
Function (){
Emit (this. group_id, this. Count );
}
';

$ Reduce ='
Function (Key, values ){
VaR sum = 0;

For (VAR index in values ){
Sum + = values [Index];
}

Return sum;
}
';

$ Result = $ instance-> command (Array (
'Mapreduce' => 'test ',
'Map' => $ map,
'Reduce' => $ reduce
));

$ Result = iterator_to_array ($ instance-> {$ result ['result']}-> Find ());

Var_dump ($ result );

?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.