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

MongoDB에서 업데이트하고 덮어쓰기를 방지하시겠습니까?


문서로 컬렉션을 만들자 −

> db.demo601.insertOne(
...    {
...       id:1,
...       userDetails:
...          {
...             userName:"John",
...             userMailId:"John@gmail.com"
...          }
...       }
...    );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e95ff5ced011c280a0905c7")
}
>
> db.demo601.insertOne( { id:2, userDetails: { userName:"Carol",
userMailId:"Carol@gmail.com" } } );{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e95ff71ed011c280a0905c8")
}

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

> db.demo601.find();

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

{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" : { "userName" : "John", "userMailId" : "John@gmail.com" } }
{ "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" : { "userName" : "Carol", "userMailId" : "Carol@gmail.com" } }

다음은 업데이트할 쿼리입니다 -

>db.demo601.update({_id:ObjectId("5e95ff71ed011c280a0905c8")},{$set:{userMailId:"Carol@yahoo.com"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo601.find();

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

{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" :
   { "userName" : "John", "userMailId" : "John@gmail.com" }
}
{ "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" :
   { "userName" : "Carol", "userMailId" : "Carol@gmail.com" }, "userMailId" : "Carol@yahoo.com" 
}