Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB에서 조건부 upserts 또는 업데이트 수행

<시간/>

조건부 upserts 또는 업데이트의 경우 $max 연산자를 사용할 수 있습니다. 먼저 문서로 컬렉션을 생성하겠습니다.

>db.conditionalUpdatesDemo.insertOne({"_id":100,"StudentFirstScore":89,"StudentSecondScore":78,"BiggestScore":89});
{ "acknowledged" : true, "insertedId" : 100 }
>db.conditionalUpdatesDemo.insertOne({"_id":101,"StudentFirstScore":305,"StudentSecondScore":560,"BiggestScore":1050});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalUpdatesDemo.insertOne({"_id":103,"StudentFirstScore":560,"StudentSecondScore":789,"BiggestScore":880});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from a collection with the help of find() method:
> db.conditionalUpdatesDemo.find().pretty();

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : 100,
   "StudentFirstScore" : 89,
   "StudentSecondScore" : 78,
   "BiggestScore" : 89
}
{
   "_id" : 101,
   "StudentFirstScore" : 305,
   "StudentSecondScore" : 560,
   "BiggestScore" : 1050
}
{
   "_id" : 103,
   "StudentFirstScore" : 560,
   "StudentSecondScore" : 789,
   "BiggestScore" : 880
}

다음은 MongoDB에서 조건부 upserts 또는 업데이트에 대한 쿼리입니다.

> db.conditionalUpdatesDemo.update( { _id: 100 }, { $max: { "BiggestScore": 150 } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

"BiggestScore" 필드가 _id 100에 대해 값 150으로 업데이트되었는지 여부를 확인하겠습니다.

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

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : 100,
   "StudentFirstScore" : 89,
   "StudentSecondScore" : 78,
   "BiggestScore" : 150
}
{
   "_id" : 101,
   "StudentFirstScore" : 305,
   "StudentSecondScore" : 560,
   "BiggestScore" : 1050
}
{
   "_id" : 103,
   "StudentFirstScore" : 560,
   "StudentSecondScore" : 789,
   "BiggestScore" : 880
}