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

배열의 하위 항목을 설정하는 MongoDB 쿼리?

<시간/>

위치 $ 연산자를 사용할 수 있습니다. 먼저 문서로 컬렉션을 생성해 보겠습니다. −

> db.demo22.insertOne(
...    {
...       ProductId:101,
...
...       ProductDetails:
...       [
...          {
...             ProductFirstPrice: '35',
...             ProductSecondPrice: '75'
...          },
...          {
...             ProductFirstPrice: '',
...             ProductSecondPrice:''
...          },
...          {
...             ProductFirstPrice: '78',
...             ProductSecondPrice:'24'
...          }
...       ]
...    }
...
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c0b422d07d3b95082e70")
}

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

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

이것은 다음과 같은 출력을 생성합니다 -

{
   "_id" : ObjectId("5e14c0b422d07d3b95082e70"),
   "ProductId" : 101,
   "ProductDetails" : [
      {
         "ProductFirstPrice" : "35",
         "ProductSecondPrice" : "75"
      },
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : ""
      },
      {
         "ProductFirstPrice" : "78",
         "ProductSecondPrice" : "24"
      }
   ]
}

다음은 배열의 하위 항목을 설정하는 MongoDB 쿼리입니다 -

> db.demo22.update({ "ProductDetails.ProductFirstPrice" : "35" },
... { $set : { "ProductDetails.$.ProductFirstPrice" : "" }}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

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

이것은 다음과 같은 출력을 생성합니다 -

{
   "_id" : ObjectId("5e14c0b422d07d3b95082e70"),
   "ProductId" : 101,
   "ProductDetails" : [
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : "75"
      },
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : ""
      },
      {
         "ProductFirstPrice" : "78",
         "ProductSecondPrice" : "24"
      }
   ]
}