본문 바로가기

mongoDB/개념

[mongoDB] CRUD 기본 문법

Collection Url 

 

MongoDB\Collection Class — PHP Library Manual 1.10-dev

 

docs.mongodb.com

1. Insert

1-1) insertOne

$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);

 

_id : _id 추가시 데이터 id 생성 가능

 

1-2) insertMany

$insertManyResult = $collection->insertMany([
    [
        'username' => 'admin',
        'email' => 'admin@example.com',
        'name' => 'Admin User',
    ],
    [
        'username' => 'test',
        'email' => 'test@example.com',
        'name' => 'Test User',
    ],
]);

 

1-3) getInsertedCount

$insertManyResult->getInsertedCount()

Inserted 2 document(s)

 

1-4) getInsertedIds

$insertManyResult->getInsertedIds()

array(2) {
  [0]=>
  object(MongoDB\BSON\ObjectId)#11 (1) {
    ["oid"]=>
    string(24) "579a25921f417dd1e5518141"
  }
  [1]=>
  object(MongoDB\BSON\ObjectId)#12 (1) {
    ["oid"]=>
    string(24) "579a25921f417dd1e5518142"
  }
}

2. Query Documents

2-1) findOne

$document = $collection->findOne(['_id' => '94301']);

object(MongoDB\Model\BSONDocument)#13 (1) {
  ["storage":"ArrayObject":private]=>
  array(5) {
    ["_id"]=>
    string(5) "94301"
    ["city"]=>
    string(9) "PALO ALTO"
  }
}

 

2-2) find

find()는 MongoDB\Driver\Cursor 객체 반환

$cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);

foreach ($cursor as $document) {
    echo $document['_id'], "\n";
}

07302
07304
07305
07306
07307
07310

2-3) projection

결과값에서 원하는 필드값만 볼 수 있다.

$cursor = $collection->find(
    [
        'cuisine' => 'Italian',
        'borough' => 'Manhattan',
    ],
    [
        'projection' => [
            'name' => 1,
            'borough' => 1,
            'cuisine' => 1,
        ]
    ]
);

foreach($cursor as $restaurant) {
   var_dump($restaurant);
};


object(MongoDB\Model\BSONDocument)#10 (1) {
  ["storage":"ArrayObject":private]=>
  array(4) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#8 (1) {
      ["oid"]=>
      string(24) "576023c6b02fa9281da3f983"
    }
    ["borough"]=>
    string(9) "Manhattan"
    ["cuisine"]=>
    string(7) "Italian"
    ["name"]=>
    string(23) "Isle Of Capri Resturant"
  }
}
object(MongoDB\Model\BSONDocument)#13 (1) {
  ["storage":"ArrayObject":private]=>
  array(4) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#12 (1) {
      ["oid"]=>
      string(24) "576023c6b02fa9281da3f98d"
    }
    ["borough"]=>
    string(9) "Manhattan"
    ["cuisine"]=>
    string(7) "Italian"
    ["name"]=>
    string(18) "Marchis Restaurant"
  }
}

 

2-4) option

limit / sort / skip

$cursor = $collection->find(
    [],
    [
        'limit' => 5,
        'sort' => ['pop' => -1],
    ]
);

foreach ($cursor as $document) {
    printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
}

60623: CHICAGO, IL
11226: BROOKLYN, NY
10021: NEW YORK, NY
10025: NEW YORK, NY
90201: BELL GARDENS, CA

2-5) regex

$cursor = $collection->find([
    'city' => new MongoDB\BSON\Regex('^garden', 'i'),
    'state' => 'TX',
]);

foreach ($cursor as $document) {
   printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
}

78266: GARDEN RIDGE, TX
79739: GARDEN CITY, TX
79758: GARDENDALE, TX

2-6) aggregate

데이터 처리 파이프라인의 개념을 모델로 한다.

여러 단계의 파이프라인을 거쳐 연산 후 하나의 문서로 집계

 

$cursor = $collection->aggregate([
    ['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
    ['$sort' => ['count' => -1]],
    ['$limit' => 5],
]);

foreach ($cursor as $state) {
    printf("%s has %d zip codes\n", $state['_id'], $state['count']);
}

TX has 1671 zip codes
NY has 1595 zip codes
CA has 1516 zip codes
PA has 1458 zip codes
IL has 1237 zip codes

3. Update

3-1) updateOne

MongoDB\UpdateResult 객체 반환

$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$updateResult = $collection->updateOne(
    ['state' => 'ny'],
    ['$set' => ['country' => 'us']]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Matched 1 document(s)
Modified 1 document(s)

3-2) updateMany

$collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
$updateResult = $collection->updateMany(
    ['state' => 'ny'],
    ['$set' => ['country' => 'us']]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Matched 3 document(s)
Modified 2 document(s)

3-3) replaceOne

MongoDB\UpdateResult 인스턴스 반환하므로 통계에 접근 가능

$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$updateResult = $collection->replaceOne(
    ['name' => 'Bob'],
    ['name' => 'Robert', 'state' => 'ca']
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Matched 1 document(s)
Modified 1 document(s)

3-4) option

upsert

일치하는 문서가 없다면 새로운 문서를 생성하여 삽입

 

$updateResult = $collection->updateOne(
    ['name' => 'Bob'],
    ['$set' => ['state' => 'ny']],
    ['upsert' => true]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());

$upsertedDocument = $collection->findOne([
    '_id' => $updateResult->getUpsertedId(),
]);

Matched 0 document(s)
Modified 0 document(s)
Upserted 1 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) {
  ["storage":"ArrayObject":private]=>
  array(3) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#15 (1) {
      ["oid"]=>
      string(24) "57509c4406d7241dad86e7c3"
    }
    ["name"]=>
    string(3) "Bob"
    ["state"]=>
    string(2) "ny"
  }
}

 

3-5) getMatchedCount

3-6) getModifiedCount

3-7) getUpsertedCount

4. Delete

4-1) deleteOne

MongoDB\DeleteResult 객체 반환

$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteOne(['state' => 'ny']);

printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

Deleted 1 document(s)

4-2) deleteMany

$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteMany(['state' => 'ny']);

printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

Deleted 2 document(s)

4-3) getDeletedCount