Data manipulation for the Mongodb for PHP tutorial

Source: Internet
Author: User
Tags findone mongodb tutorial php tutorial

Common operations for MongoDB

See the Manual, PHP official http://us2.php.net/manual/en/mongo.manual.php

You can also see the official MongoDB tutorial

Database connection

⑴ default Format

$m = new Mongo ();

This is the default connection to the local 27017 port, of course you can also connect the remote host such as 192.168.0.4:27017, if the port is 27017, the port can be omitted

⑵ Standard Connection

$m = new Mongo ("Mongodb://${username}:${password} @localhost");

Example: $m = new Mongo ("Mongodb://127.0.0.1:27017/admin:admin");

The user name and password for the database are both admin

Database operations:

Insert data:

+ View Code

  

Results:

Query with conditions

Querying for fields with the title Huaibei

1 $query = Array ("title" = "Huaibei");

2 $cursor = $collection->find ($query); Find documents that meet $query in the $collectio collection

Common SQL conversions to MongoDB conditions

Mysql:id = 123

Mongo:array (' id ' =>123)

Mysql:name Link '%bar% '

Mongo:array (' name ' = = new Mongoregex ('/.*bar.*/i '))

Mysql:where ID > 10

Mongo:array (' id ' = = Array (' $gt ' = 10))

Mysql:where ID >= 10

Mongo:array (' id ' = = Array (' $gte ' = 10))

Mysql:where ID < 10

Mongo:array (' id ' = = Array (' $lt ' = 10))

Mysql:where ID <= 10

Mongo:array (' id ' = = Array (' $lte ' = 10))

Mysql:where ID > 1 and ID < 10

Mongo:array (' id ' = = Array (' $gt ' = + 1, ' $lt ' = + 10))

Mysql:where ID <> 10

Mongo:array (' id ' = = Array (' $ne ' = 10))

Mysql:where ID in (123)

Mongo:array (' id ' = = Array (' $in ' = = Array ()))

Mysql:where ID not in (123)

Mongo:array (' id ' = = Array (' $nin ' = = Array ()))

Mysql:where id = 2 or id = 9

Mongo:array (' id ' = = Array (' $or ' = = Array (' ID ' =>2), array (' ID ' =>9)))

Mysql:order by name ASC

Mongo:array (' Sort ' =>array (' name ' =>1)

Mysql:order by name Desc

Mongo:array (' Sort ' =>array (' name ' =>-1)

Mysql:limit 0,2

Mongo:array (' Limit ' =>array (' offset ' =>0, ' rows ' =>2)

Mysql:select Name,email

Mongo:array (' name ', ' email ')

Mysql:select count (name)

Mongo:array (' count ')//NOTE: COUNT is uppercase

More detailed conversion Reference http://us2.php.net/manual/en/mongo.sqltomongo.php

Precautions

When querying, each object is automatically generated with a unique _id, which is equivalent to the primary key in the RDBMS, which is very convenient for querying (_id each different, much like an auto-incremented ID)
Such as:

1 <?php  2   3 $person= array("name"=> "joe");  4   5 $people->insert($person);  6   $joe= $people->findOne(array("_id"=> $person[‘_id‘]));  8   9 ?> 

  

Data changes

Add a new Field

/** Original field:
* {"username": "...", "Password": "...", "email": "..."}
*/
$coll->update ("username" and "Joe"), Array (' $set ' = = Array ("twitter" = "@joe4153"));

/** the field after the operation:
* {"username": "Joe", "Password": "...", "email": "...", "Twitter": "@joe4153"}
*/

Change field values

/** Raw Data
* {"username": "...", "Password": "...", "email": "..."}
*/
$coll->update ("username" and "Joe"), Array ("userId" = 12345, "info" = = Array (
"Name" and "Joe", "Twitter" and "@joe4153", "email" and "...", "likes" and "=" ());

/** the data after the operation:
* {
* "UserId": 12345,
* "Info": {
* "Name": "Joe",
* "Twitter": "@joe4153",
* "Email": "..."
*     },
* "Likes": []
* }
*/

More complex updates

Change the name of author to John

{

"_id": ObjectId ("4b06c282edb87a281e09dad9"),

"Content": "This is a blog post.",

"Comments":

[

{

"Author": "Mike",

"Comment": "I think that blah blah blah ...",

},

{

"Author": "John",

"Comment": "I disagree."

}

]

}

Action: <?php

$blog->update (
Array ("Comments.author" = "John"),
Array (' $set ' = = Array (' Comments.$.author ' + "Jim"));

?>

Delete a database

$m-dropdb ("comedy");

List all available databases

$m->listdbs (); No return value

Reproduced part of MongoDB Common database method

Functions that are useful in MongoDB:

Create a MongoDB object

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

$mo = new Mongo ();

$db = new MongoDB ($mo, ' dbname ');//Get a MongoDB object by creating a method

Delete Current db

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

$db = $mo->dbname;

$db->drop ();

Get 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->collname;

D:

$db = $mo->dbname;

$coll = $db->selectcollectoin (' collname ');//Get a Collection Object

Insert data (Mongocollection object):

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

Mongocollection::insert (array $a, array $options)

Array $a arrays to insert

Array $options Options


Does safe return operation result Information

Fsync is inserted directly into the physical hard disk

Routines:

$coll = $mo->db->foo;

$a = Array (' a ' = = ' B ');

$options = Array (' safe ' =>true);

$rs = $coll->insert ($a, $options);

$rs an array of type array that contains the operation information

To delete a record in a database (Mongocollection object):

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

Mongocollection::remove (array $criteria, array $options)

Array $criteria conditions

Array $options Options

Does safe return operation results

Whether the fsync is directly affecting the physical hard disk

Does justone affect only one record

Routines:

$coll = $mo->db->coll;

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

$options = Array (' safe ' =>true);

$rs = $coll->remove ($c, $options);

$rs an array of type array that contains the operation information

Update records in the database (Mongocollection objects):

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

Mongocollection::update (array $criceria, array $newobj, array $options)

Array $criteria conditions

Array $newobj What to update

Array $options Options

Does safe return operation results

Whether the fsync is directly affecting the physical hard disk

Upsert If there is no matching data, add a new

Multiple affects all eligible records by default, only one

Routines:

$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 an array of type array that contains the operation information

Query collection get a single record (Mongocollection Class):

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

Array Mongocollection::findone (array $query, array $fields)

Array $query conditions

Array $fields the field to get

Routines:

$coll = $mo->db->coll;

$query = Array (' s ' =>array (' $lt ' =>100));

$fields = Array (' A ' =>true, ' B ' =>true);

$rs = $coll->findone ($query, $fields);

Returns an array if there is a result, and returns null if there is no result

Query collection get multiple records (Mongocollection Class):

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

Mongocursor mongocollection::find (array $query, array $fields)

Array $query conditions

Array $fields the field to get

Routines:

$coll = $mo->db->coll;

$query = Array (' s ' =>array (' $lt ' =>100));

$fields = Array (' A ' =>true, ' B ' =>true);

$cursor = $coll->find ($query, $fields);

Sort

$cursor->sort (Array (' field ' =>-1));(-1 reverse, 1 positive order)
Skipping part of a record

$cursor->skip (100); Skip 100 lines

Show only partial records

$cursor->limit (100); Show only 100 rows

Returns a cursor Record object mongocursor.

Action on Cursor Object Mongocursor (Mongocursor 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);

**************************************************************************

MongoDB Introduction Installation Common operation has been introduced, in fact, it feels like he is MySQL, now you can enter your development journey, it is recommended to use this as a background log system database.

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.