PHP操作MongoDB(增刪改查)

原文鏈接:https://www.cnblogs.com/wujuntian/p/8352586.html

PHP操作MongoDB(增刪改查)

  MongoDB的PHP驅動提供了一些核心類來操作MongoDB,總的來說MongoDB命令行中有的功能,它都可以實現,而且參數的格式基本相似。PHP7以前的版本和PHP7之後的版本對MongoDB的操作有所不同,本文主要以PHP7以前版本爲例講解PHP對MongoDB的各種操作,最後再簡單說明一下PHP7以後版本對MongoDB的操作。

一、數據插入

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

//insert()

//參數1:一個數組或對象

//參數2:擴展選項

//  fsync:默認爲false,若爲true則mongo在確認數據插入成功之前將會強制把數據寫入硬盤

//  j:默認爲false,若爲true則mongo在確認數據插入成功之前將會強制把數據寫入日誌

//  w:默認爲1,寫操作會被(主)服務器確認,若爲0則將不會得到確認,使用複製集時設置爲n用於確保主服務器將數據修改成功複製到n個節點後再確認

//  wtimeout:默認爲10000(毫秒),用於指定服務器等待接收確認的時間

//  timeout:指定客戶端需要等待服務器響應的超時時間(毫秒)

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;//選擇數據庫

$collection = $db->friend;//選擇文檔集合

$doc = [//定義一個文檔,即一個數組

    'First Name' => 'Jet',

    'Last Name' => 'Wu',

    'Age' => 26,

    'Phone' => '110',

    'Address' => [

        'Country' => 'China',

        'City' => 'Shen Zhen'

    ],

    'E-Mail' => [

        '[email protected]',

        '[email protected]',

        '[email protected]',

        '[email protected]'

    ]

];

$res = $collection->insert($doc);//向集合中插入一個文檔

echo '<pre>';

print_r($res);//$res['ok']=1表示插入成功

  

二、數據查詢

1. 查詢單個文檔:

?

1

2

3

4

5

6

7

8

9

//findOne()

//參數1:搜索條件

//參數2:指定返回字段,array('fieldname' => true, 'fieldname2' => true)。_id字段總會返回,除非在第二個參數顯式加入'_id'=>false。不設置則返回所有字段

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$one = $collection->findOne(['First Name' => 'Jet']);

echo '<pre>';

print_r($one);//返回一個數組,查不到數據則返回NULL

2. 查詢多個文檔:

?

1

2

3

4

5

6

7

8

9

10

11

//find()

//參數1:搜索條件

//參數2:指定返回字段,array('fieldname' => true, 'fieldname2' => true)。_id字段總會返回,除非顯式設置爲false不返回。不設置則返回所有字段

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$cursor = $collection->find(['Address.Country' => 'China']);//使用點操作符查找數組元素

echo '<pre>';

while($doc = $cursor->getNext()) {//循環讀取每個匹配的文檔

    print_r($doc);

}

使用各種條件操作符定義查詢:

?

1

2

3

4

5

6

7

8

9

//mongodb分別使用$lt、$lte、$eq、$gte、$gt、$ne表示<、<=、=、>=、>、<>,用於整數字段查詢

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$cursor = $collection->find(['Age' => ['$gt' => 30]]);

echo '<pre>';

while($doc = $cursor->getNext()) {

    print_r($doc);

}

  //查詢某個字段的所有不重複的值
  $res = $collection->distinct('Age');

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

//$in:匹配多個值中任意一個

$cursor = $collection->find(['Address.Country' => ['$in' => ['China', 'USA']]]);

 

//$all:匹配多個值中所有值(用於數組字段查詢)

$cursor = $collection->find(['E-Mail' => ['$all' => ['[email protected]', '[email protected]']]]);

 

//$or:或查詢

$cursor = $collection->find(['$or' => [['First Name' => 'Jet'], ['Address.Country' => 'USA']]]);

 

//$slice:獲取數組字段中指定數目的元素,位於find()函數第二個參數中

$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => 2]]);//只返回前兩個email

$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => -2]]);//只返回最後兩個email

$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => [1, 2]]]);//忽略第一個,返回接下來兩個

 

//$exists:根據某個字段是否有設置值進行查詢

$cursor = $collection->find(['Hobby' => ['$exists' => false]]);//查找Hobby字段未設置值的文檔

 

//正則表達式查詢

$cursor = $collection->find(['First Name' => new MongoRegex('/^Je/i')]);//查找First Name字段以Je開頭的文檔,忽略大小寫差異

使用MongoCursor類提供的其他函數:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//排序:1升序,-1降序

$cursor->sort(['Age' => 1]);

 

//忽略前n個匹配的文檔

$cursor->skip(1);

 

//只返回前n個匹配的文檔(limit()與skip()結合使用可實現數據分頁功能)

$cursor->limit(1);

 

//匹配文檔的總數

$cursor->count();

 

//指定查詢索引

$cursor->hint(['Last Name' => -1]);//若索引不存在則會報錯

聚集查詢:對數據進行分組統計

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

//聚合查詢:對數據進行分組統計

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$res = $collection->aggregate([

    '$group' => [

        '_id' => '$Address.Country',//分組字段,注意要加上“$”,這裏是根據數組字段某個元素值進行分組

        'total' => ['$sum' => 1],//求總和,表示每匹配一個文檔總和就加1

        'maxAge' => ['$max' => '$Age'],//分組中Age字段最大值

        'minAge' => ['$min' => '$Age']//分組中Age字段最小值

    ]

]);

echo '<pre>';

print_r($res);//返回一個數組,$ret['result']爲數組,存放統計結果

 

 

//存在其它操作的聚合查詢:多個操作之間執行先後順序取決於它們位置的先後順序

//聚合查詢中的所有操作,包括'$group'在內,都是可選的。

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$res = $collection->aggregate([

    [//過濾條件:只對符合條件的原始文檔進行聚合運算,若是放在'$group'之後則是隻返回符合條件的結果文檔

        '$match' => ['Age' => ['$gt' => 30]]

    ],

    [//指定分組字段、統計字段

        '$group' => [

            '_id' => '$Address.Country',

            'totalAge' => ['$sum' => '$Age']//計算各個分組Age字段總和

        ]

    ],

    //以下操作若是放在'$group'之前則在聚合前作用於原始文檔,若放在'$group'之後則在聚合後作用於結果文檔

    ['$unwind' => '$E-Mail'],//將包含有某個數組類型字段的文檔拆分成多個文檔,每個文檔的同名字段的值爲數組中的一個值。

    ['$project' => ['myAge' => '$Age', 'First Name' => '$First Name']],//指定返回字段,可以對字段進行重命名,格式:返回字段名 => $原來字段名

    ['$skip' => 2],//跳過指定數量的文檔

    ['$limit' => 2],//只返回指定數量的文檔

    ['$sort' => ['totalAge' => 1]]//排序

]);

echo '<pre>';

print_r($res);

 

三、數據修改

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

//update()

//參數1:更新條件,指定更新的目標對象。

//參數2:指定用於更新匹配記錄的對象。

//參數3:擴展選項組。

//  upsert:若設置爲true,當沒有匹配文檔的時候會創建一個新的文檔。

//  multiple:默認爲false,若設置爲true,匹配文檔將全部被更新。

//  fsync:若設置爲true,w參數將被覆蓋爲0,數據將在更新結果返回前同步到磁盤。

//  w:默認爲1;若設置爲0,更新操作將不會得到確認;使用複製集時可設置爲n,確保主服務器在將修改複製到n個節點後才確認該更新操作

//  j:默認爲false,若設置爲true,數據將在更新結果返回之前寫入到日誌中。

//  wtimeout:默認爲10000(毫秒),用於指定服務器等待接收確認的時間

//  timeout:指定客戶端需要等待服務器響應的超時時間(毫秒)

//注意:若不使用任何修改操作符,則匹配文檔將直接被整個替換爲參數2指定的對象。

 

//$inc:增加特定鍵的值,若字段不存在則新建字段並賦值

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$res = $collection->update(['First Name' => 'Jet'], ['$inc' => ['Age' => 2]]);

echo '<pre>';

print_r($res);//$res['ok']=1表示修改成功,$res['nModified']表示修改的文檔數量

 

//$set:重置特定鍵的值,若字段不存在則新建字段並賦值

$res = $collection->update(['First Name' => 'Jet'], ['$set' => ['Hobby' => 'pingpong']]);

 

//$unset:刪除字段

$res = $collection->update(['First Name' => 'Jet'], ['$unset' => ['Hobby' => 1]]);

 

//$rename:重命名字段,若字段不存在則不進行任何操作

$res = $collection->update(['First Name' => 'Jet'], ['$rename' => ['Hobby' => 'hobby', 'Age' => 'age']]);

//注意:如果文檔中已經使用了指定名稱的字段,則該字段將會被刪除,然後再進行重命名操作。

 

//$setOnInsert:設置了upsert爲true,並且發生了插入操作的時候,將某個字段設置爲特定的

$res = $collection->update(['First Name' => 'jet'], ['$setOnInsert' => ['lang' => 'English']], ['upsert' => true]);

 

//$push:向指定字段添加一個值(作用於數組字段),若字段不存在會先創建字段,若字段值不是數組會報錯

$res = $collection->update(['First Name' => 'Jet'], ['$push' => ['E-Mail' => '[email protected]']]);

 

//$push:向指定字段添加多個值(作用於數組字段),若字段不存在會先創建字段,若字段值不是數組會報錯

$res = $collection->update(['First Name' => 'Jet'], ['$pushAll' => ['E-Mail' => ['[email protected]', '[email protected]']]]);

 

//使用$push和$each向某個字段添加多個值(作用於數組字段),若字段不存在會先創建字段,若字段值不是數組會報錯

$res = $collection->update(['First Name' => 'Jet'], ['$push' => ['E-Mail' => ['$each' => ['[email protected]', '[email protected]']]]]);

 

//$addToSet:將數據添加到數組中(只在目標數組沒有該數據的時候纔將數據添加到數組中)

$res = $collection->update(['First Name' => 'Jet'], ['$addToSet' => ['E-Mail' => '[email protected]']]);

$res = $collection->update(['First Name' => 'Jet'], ['$addToSet' => ['E-Mail' => ['$each' => ['[email protected]', '[email protected]']]]]);

 

//$pop:從數組中刪除一個元素,-1表示刪除第一個元素,1表示刪除最後一個元素(其實負數都刪除第一個元素,0或正數都刪除最後一個元素)

$res = $collection->update(['First Name' => 'Jet'], ['$pop' => ['E-Mail' => 1]]);

 

//$pull:刪除數組中所有指定值

$res = $collection->update(['First Name' => 'Jet'], ['$pull' => ['E-Mail' => '[email protected]']]);

 

//$pullAll:刪除數組中多個元素的所有值

$res = $collection->update(['First Name' => 'Jet'], ['$pullAll' => ['E-Mail' => ['[email protected]', '[email protected]']]]);

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

//save()

//參數1:希望保存的信息數組

//參數2:擴展選項

//  fsync:若設置爲true,w參數將被覆蓋爲0,數據將在更新結果返回前同步到磁盤。

//  w:默認爲1;若設置爲0,更新操作將不會得到確認;使用複製集時可設置爲n,確保主服務器在將修改複製到n個節點後才確認該更新操作

//  j:默認爲false,若設置爲true,數據將在更新結果返回之前寫入到日誌中。

//  wtimeout:默認爲10000(毫秒),用於指定服務器等待接收確認的時間

//  timeout:指定客戶端需要等待服務器響應的超時時間(毫秒)

//注意:若已存在則更新,若不存在則插入;更新時使用參數1指定的信息數組替換整個文檔。

//若想更新則應該在參數1中指定_id鍵的值。

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$doc = [//定義一個文檔,即一個數組

    'First Name' => 'Jet',

    'Last Name' => 'Wu',

    'Age' => 26,

    'Phone' => '110',

    'Address' => [

        'Country' => 'China',

        'City' => 'Shen Zhen'

    ],

    'E-Mail' => [

        '[email protected]',

        '[email protected]',

        '[email protected]',

        '[email protected]'

    ]

];

$res = $collection->save($doc);

echo '<pre>';

print_r($res);//$res['ok']=1表示操作成功,$res['updatedExisting']=1表示更新,$res['upserted']=1表示插入

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//findAndModify()

//參數1:指定查詢條件

//參數2:指定用於更新文檔的信息

//參數3:可選,指定希望返回的字段

//參數4:擴展選項

//  sort:以特定順序對匹配文檔進行排序

//  remove:若設置爲true,第一個匹配文檔將被刪除

//  update:若設置爲true,將在被選擇的文檔上執行更新操作

//  new:默認爲false,若設置爲true則返回更新後的文檔,否則返回更新前的文檔

//  upsert:若設置爲true,沒有找到匹配文檔的時候將插入一個新的文檔

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$res = $collection->findAndModify(['First Name' => 'Jet'], ['$push' => ['E-Mail' => '[email protected]']]);

echo '<pre>';

print_r($res);

  

四、數據刪除

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//remove()

//參數1:查詢條件

//參數2:擴展選項

//  justOne:若設置爲true,則最多隻有一個匹配的文檔將被刪除

//  fsync:若設置爲true,w參數將被覆蓋爲0,數據將在更新結果返回前同步到磁盤。

//  w:默認爲1;若設置爲0,更新操作將不會得到確認;使用複製集時可設置爲n,確保主服務器在將修改複製到n個節點後才確認該更新操作

//  j:默認爲false,若設置爲true,數據將在更新結果返回之前寫入到日誌中。

//  wtimeout:默認爲10000(毫秒),用於指定服務器等待接收確認的時間

//  timeout:指定客戶端需要等待服務器響應的超時時間(毫秒)

$mongo = new MongoClient('mongodb://localhost:27017');

$db = $mongo->mf;

$collection = $db->friend;

$res = $collection->remove(['First Name' => 'jet']);

echo '<pre>';

print_r($res);//$res['n']表示刪除了幾個文檔

 

以上是PHP7以前版本的MongoDB操作,下面簡單介紹PHP7以後版本的操作。

 

-----------------------------------------------PHP7分隔線---------------------------------------------------------------------

 

數據插入:

?

1

2

3

4

5

6

7

8

9

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$bulk = new MongoDB\Driver\BulkWrite;

$bulk->insert(['name' => 'JetWu5', 'age' => 26]);

$bulk->insert(['name' => 'JetWu6', 'age' => 26]);

 

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可選,修改確認

$res = $manager->executeBulkWrite('wjt.friend', $bulk, $writeConcern);

echo '<pre>';

print_r($res);

 

數據查詢:

?

1

2

3

4

5

6

7

8

9

10

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$query = new MongoDB\Driver\Query(['age' => 24], ['sort' => ['age' => 1]]);

$cursor = $manager->executeQuery('wjt.friend', $query);

 

$data = [];

foreach($cursor as $doc) {

    $data[] = $doc;

}

echo '<pre>';

print_r($data);

  

數據修改:

?

1

2

3

4

5

6

7

8

9

10

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$bulk = new MongoDB\Driver\BulkWrite;

$bulk->update(

    ['name' => 'JetWu5'],

    ['$set' => ['age' => 30, 'promise' => 'always smile!']]

);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可選,修改確認

$res = $manager->executeBulkWrite('wjt.friend', $bulk, $writeConcern);

echo '<pre>';

print_r($res);

  

數據刪除:

?

1

2

3

4

5

6

7

8

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$bulk = new MongoDB\Driver\BulkWrite;

$bulk->delete(['name' => 'JetWu3']);

$bulk->delete(['name' => 'JetWu4']);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可選,修改確認

$res = $manager->executeBulkWrite('wjt.friend', $bulk, $writeConcern);

echo '<pre>';

print_r($res);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章