2014-11-12 4 views
0

"_id"및 "ProductLot"이 있습니다. ProductLot (있는 경우) 또는 존재하지 않는 경우 새 Lot 요소를 추가하면 Lot 배열에서 수량을 "0"에서 "1"로 업데이트 할 수 있습니까?MongoDB : 배열에 삽입 및 업데이트

"_id" : ObjectId("5462e44c599e5c6c1300000a"), 
"LocationName" : "Putaway", 
"Owner" : "", 
"Status" : "1", 
"Scrap" : "0", 
"Lot" : [{  
    "Qty" :"6", 
    "ProductLot" : ObjectId("5462dbd9599e5c200e000000"), 
    "Product" : ObjectId("543ca7be4cf59d400c000004"),  
    "Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"}, 
      {"OriginId" : "267" , Qty:1 , Type:"DN"}, 
      {"OriginId" : "2" , Qty:3 , Type:"IM"}, 

     ] 
    }, 
    {  
    "Qty" :"0", 
    "ProductLot" : ObjectId("5462dbd9599e5c200e000003"), 
    "Product" : ObjectId("543ca7be4cf59d400c000004"),  
    "Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"}, 
      {"OriginId" : "267" , Qty:1 , Type:"DN"}, 
      {"OriginId" : "2" , Qty:-3 , Type:"IM"}, 
     ] 

    }] 
} 

EG : I "는 ProductLot"가지고 그 수량 0 1 업데이트해야하므로 본 ObjectId가 배열 ("5462dbd9599e5c200e000000을"); 그러나 "ProductLot": ObjectId ("5462dbd9599e5c200e00000a")를 배열에서 사용할 수 없으므로 배열에 새 요소를 추가해야합니다. 모든 시간에 추가 배열을 생성 업데이트되지

PHP 코드 :

  $inventoryId = new \MongoId($_POST["inventoryid"]); 
      $productLotId = new \MongoId($invlotid); 
      $originId = $_POST['id']; 
      //$lotcontent = [ /* whatever this looks like */ ]; 

      $lotcontent = array(
        'Qty' => $invqty, 
        'ProductLot' => new \MongoId($invlotid), 
        'Product'=>$invproduct, 
        'Movement'=> array(
          array(
          'OriginId' => $_POST['id'], 
          'Qty' => $invqty, 
          'Type'=> 'DN',    
          ), )     
        ); 
      $invcolname = 'Inventory'; 
      $result = $mongo->$dbname->$invcolname->update(
      // Match an inventory without the specific ProductLot/OriginId element 
      array(
       '_id' => $inventoryId, 
       'Lot' => array(
        '$not' => array(
         '$elemMatch' => array(
          'ProductLot' => $productLotId, 
          //'OriginId' => $originId, 
         ), 
        ), 
       ), 
      ), 
      // Append a new element to the Lot array field 
      array('$push' => array('Lot' => $lotcontent)) 
      ); 

      $movementcontent = array(
          'OriginId' => $_POST['id'], 
          'Qty' => $invqty, 
          'Type'=> 'DN',    
          ); 

      $result = $mongo->$dbname->$invcolname->update(
      // Match an inventory without the specific ProductLot/OriginId element 
      array(
       '_id' => $inventoryId, 
       'Lot' => array(
        //'$not' =>  array(
         '$elemMatch' => array(
          'ProductLot' => $productLotId,        
          'Movement'=>array(
           '$not' => array(
            '$elemMatch' => array(
             'OriginId' => $originId, 
            ) 
           ) 
          )        
         ), 
        //), 
       ), 
      ), 
      // Append a new element to the Lot.Movement array field 
      array('$push' => array('Lot.$.Movement' => $movementcontent)) 
      ); 


      $result = $mongo->$dbname->$invcolname->update(
       // Match an inventory with a specific ProductLot/OriginId element 
       array(
        '_id' => $inventoryId, 
        'Lot' => array(
         '$elemMatch' => array(
          'ProductLot' => $productLotId, 
          //'OriginId' => $originId, 
          'Movement'=>array(
           '$elemMatch' => array(
             'OriginId' => $originId, 
            ) 
          ) 
         ), 
        ), 
       ), 
       // Update the "Qty" field of the first array element matched (if any)     
       //array('$set' => array('Lot.$.Qty' => 'Updated')), 
       array('$set' => array('Lot.$.Movement.$.Qty' => $invqty)), 
      array('upsert' => true));    

사람이 제발 도와주세요은이 문제를 해결하려면? 다음 lot 요소가 다른 간주 될 수 있기 때문에 $addToSet를 사용

+0

$ 세트는 당신이 찾고있는 것입니다! Google은 친구입니다 – Sekai

답변

1

,이 경우에 문제가 :

{ 
    "Qty" :0, 
    "ProductLot" : ObjectId("5462dbd9599e5c200e000003"), 
    "Product" : ObjectId("543ca7be4cf59d400c000004"), 
    "OriginId" : "266" 
} 

{ 
    "Qty" :5, 
    "ProductLot" : ObjectId("5462dbd9599e5c200e000003"), 
    "Product" : ObjectId("543ca7be4cf59d400c000004"), 
    "OriginId" : "266" 
} 

첫 번째 요소는 당신이 추가 될 것 같다 (수량 0 또는 중 1) 및 두 번째 요소는 동일한 논리적 로트 요소가되며 증분 된 수량 만 있습니다. 후자의 요소가 이미 배열에 존재했다면, 본질적으로 중복 요소 인 첫 번째 요소를 추가하는 대신 응용 프로그램에서 수량을 5에서 6으로 증가시키고 싶다고 생각합니다.

우리는 확실히 여기에 두 개의 업데이트가 필요하지만, 나는 다음을 제안합니다 :

// Let's assume the following identifiers... 
$inventoryId = new MongoId($_POST['inventoryid']); 
$productLotId = new MongoId($invlotid); 
$originId = new MongoId($_POST['id']); 
$lotcontent = [ /* whatever this looks like */ ]; 

$result = $collection->update(
    // Match an inventory without the specific ProductLot/OriginId element 
    [ 
     '_id' => $inventoryId, 
     'Lot' => [ 
      '$not' => [ 
       '$elemMatch' => [ 
        'ProductLot' => $productLotId, 
        'OriginId' => $originId, 
       ], 
      ], 
     ], 
    ], 
    // Append a new element to the Lot array field 
    [ '$push' => [ 'Lot' => $lotcontent ] ] 
); 

MongoCollection::update()가 영향을받는 문서의 수를 나타내는 n 필드와 결과 문서를 반환합니다. multiple 옵션을 사용하지 않고 대부분 하나의 문서에서 _id으로 일치하는 경우 n은 0 또는 1이 될 수 있습니다. n이 0 인 경우 해당 _id 인벤토리 문서를 찾을 수 없거나 하나를 발견했지만 이미 제품 및 원산지 식별자가있는 Lot 요소 (예 : $elemMatch 기준이 무언가와 일치하여 부정을 무효화 함)가 있습니다. n이 1 인 경우 인벤토리 문서를 찾았고 일치하는 Lot 요소가 없으므로 인벤토리 문서를 추가하고 추가했습니다 (즉, 작업이 완료되었습니다).

$result = $collection->update(
    // Match an inventory with a specific ProductLot/OriginId element 
    [ 
     '_id' => $inventoryId, 
     'Lot' => [ 
      '$elemMatch' => [ 
       'ProductLot' => $productLotId, 
       'OriginId' => $originId, 
      ], 
     ], 
    ], 
    // Update the "Qty" field of the first array element matched (if any) 
    [ '$inc' => [ 'Lot.$.Qty' => 1 ] ] 
); 

를 자, 내가이 기준에 일치 된 특정 배열 요소에 액세스 할 수 $ positional update operator을 사용하고 있습니다 : 가정 n

우리가 또 다른 업데이 트를 발행하고 양을 증가하려고한다, 0이었다. 이렇게하면 일치하는 요소의 색인을 염려하지 않고 $inc을 만들 수 있습니다.

다시 여기에서 $result['n']을 확인할 수 있습니다. 그래도 0 인 경우 _id과 일치하는 문서가 없다고 가정 할 수 있습니다 (완전히 별개의 오류). 그러나이 시점에서 n이 1이면 성공적으로 수량이 증가하고 작업이 완료됩니다.

+0

'$ inc'사용 중 - 오류 : 'MongoCursorException'with message ': 비 숫자 인수로 증가 할 수 없습니다 : {Lot. $. Qty : "4"}' – Silviaa

+0

중첩 배열 gettin을 업데이트하려고합니다. 오류 : db.Inventory.update ({ "_ id": ObjectId ("5462e44c599e5c6c13000000"), "Lot."$ 25", "ProductLot": ObjectId ("54648649599e5c1c06000003"), "Lot.Movement.OriginId": "267"}, { "Lot. $. 운동량. 수량": "9"}) – Silviaa

+0

'$ inc' 오류 당신이 공유하고 있다면, 당신은''4 ''(문자열)을 증분 값으로 사용하고 있습니다. 당신은'4 '(숫자)를 사용해야합니다. PHP 사이의 느슨한 형 변환은 BSON으로 확장되지 않습니다 .. – jmikola