Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 한 번의 업데이트 호출로 두 개의 개별 배열 업데이트하기 ($push 연산자 활용)

MongoDB에서 한 번의 update 호출로 문서 내 두 개의 개별 배열을 동시에 업데이트하고 싶다면 $push 연산자를 사용하면 됩니다. 이 글에서는 실제 예제를 통해 그 과정을 단계별로 살펴보겠습니다.

1단계: 샘플 컬렉션 생성하기

먼저 학생 이름과 두 개의 게임 점수 배열(StudentFirstGameScore, StudentSecondGameScore)을 담은 문서 세 개를 삽입하여 컬렉션을 만들어 보겠습니다.

>db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152815e86fd1496b38b8")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152d15e86fd1496b38b9")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b153315e86fd1496b38ba")
}

2단계: find() 메서드로 전체 문서 조회하기

다음은 find() 메서드를 사용해 컬렉션의 모든 문서를 출력하는 쿼리입니다.

> db.twoSeparateArraysDemo.find().pretty();

위 쿼리는 아래와 같은 결과를 반환합니다.

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58
   ],
   "StudentSecondGameScore" : [
      78
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}

3단계: 한 번의 업데이트로 두 배열에 동시에 값 추가하기

다음 쿼리는 $push 연산자 안에 두 개의 필드를 함께 지정하여, 단 한 번의 update 호출로 서로 다른 두 배열에 각각 새로운 값을 추가합니다.

> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
   StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

실행 결과에서 nModified가 1로 표시되는 것으로 보아, 해당 문서가 정상적으로 수정되었음을 알 수 있습니다.

4단계: 업데이트 결과 확인하기

이제 두 개의 개별 배열에 값이 제대로 추가되었는지 다시 조회해 보겠습니다.

> db.twoSeparateArraysDemo.find().pretty();

실행 결과는 다음과 같습니다.

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58,
      45
   ],
   "StudentSecondGameScore" : [
      78,
      99
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}

출력 결과를 보면 Mike의 문서(ObjectId: 5c9b152d15e86fd1496b38b9)에서 StudentFirstGameScore 배열에는 45가, StudentSecondGameScore 배열에는 99가 각각 추가된 것을 확인할 수 있습니다. 이처럼 $push 연산자 하나에 여러 필드를 나열하기만 하면, 별도의 업데이트 호출 없이 한 번의 요청만으로 여러 배열을 동시에 수정할 수 있습니다.