이것은 MongoDB에서 업서팅을 수행하는 방법입니다.

2386 단어 mongodb


MongoDB에 대한 전체 개요와 그에 대한 모든 게시물을 보려면 내 overview 를 확인하십시오.

Upserting은 MongoDB가 지원하는 삽입과 업데이트를 결합한 데이터베이스 개념입니다. 업데이트 작업 중에 upsert를 수행하려면 update , updateOne 또는 updateMany 메서드에 추가 인수를 전달해야 합니다.

주어진 데이터가 users라는 컬렉션에 삽입된 경우:

db.users.insertMany([
    {
        _id: 1,
        name: "John Doe",
        email: "[email protected]",
        admin: true
    },
    {
        _id: 2,
        name: "Jane Doe",
        email: "[email protected]",
        admin: true
    },
    {
        _id: 3,
        name: "Billy Bob",
        email: "[email protected]",
        admin: false
    },
    {
        _id: 4
        name: "Steve Stevenson",
        email: "[email protected]",
        admin: true
    },
])



다음 명령을 사용하는 경우:

db.users.updateOne({_id: 5}, {$set: {admin: true}})


_id = 5 의 쿼리와 일치하는 문서가 없으므로 아무 작업도 수행하지 않습니다.

업서팅이 활성화된 경우:

db.users.updateOne(
    {_id: 5},
    { $set: { admin: true } },
    { upsert: true }
)



쿼리와 일치하는 문서가 없으므로 지정된_id 및 업데이트 연산자의 결과를 사용하여 새 문서가 삽입됩니다.

Use the find method to read data back out of MongoDB 컬렉션을 확인하려면:

db.users.find()



결과:

{
    _id: 1,
    name: "John Doe",
    email: "[email protected]",
    admin: true
},
{
    _id: 2,
    name: "Jane Doe",
    email: "[email protected]",
    admin: true
},
{
    _id: 3,
    name: "Billy Bob",
    email: "[email protected]",
    admin: false
},
{
    _id: 4
    name: "Steve Stevenson",
    email: "[email protected]",
    admin: true
},
{
    _id: 5
    admin: true
}

좋은 웹페이지 즐겨찾기