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

MongoDB의 기존 레코드에 필드를 어떻게 추가합니까?

<시간/>

업데이트 명령을 사용하여 기존 레코드에 필드를 추가할 수 있습니다. 먼저 문서로 컬렉션을 생성해 보겠습니다. −

> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00e32588d4a6447b2e061")
}
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00e59588d4a6447b2e062")
}

다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -

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

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

{
   "_id" : ObjectId("5cd00e32588d4a6447b2e061"),
   "ClientName" : "Chris",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cd00e59588d4a6447b2e062"),
   "ClientName" : "Robert",
   "ClientAge" : 36
}

다음은 모든 레코드에 필드를 추가하는 쿼리입니다. ClientDetails를 추가하고 있습니다 -

>db.addAFieldToEveryRecordDemo.update({},{$set:{"ClientDetails.ClientCountryName":""}},true,true);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

모든 문서가 새 레코드로 추가되었는지 확인합니다. −

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

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

{
   "_id" : ObjectId("5cd00e32588d4a6447b2e061"),
   "ClientName" : "Chris",
   "ClientAge" : 34,
   "ClientDetails" : {
      "ClientCountryName" : ""
   }
}
{
   "_id" : ObjectId("5cd00e59588d4a6447b2e062"),
   "ClientName" : "Robert",
   "ClientAge" : 36,
   "ClientDetails" : {
      "ClientCountryName" : ""
   }
}