업데이트하려면 $set과 함께 update()를 사용하십시오. 문서로 컬렉션을 만들자 −
>db.demo134.insertOne({"EmployeeId":101,"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeAge":27},{"EmployeeName":"Bob","EmployeeAge":28}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b2f68e7f832db1a7f7c") } >db.demo134.insertOne({"EmployeeId":102,"EmployeeDetails":[{"EmployeeName":"David","EmployeeAge":24},{"EmployeeName":"Carol","EmployeeAge":29}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b4468e7f832db1a7f7d") }
find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo134.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Chris", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }
다음은 MongoDB에서 하위 문서의 배열을 업데이트하는 쿼리입니다 -
> db.demo134.update( ... { ... "EmployeeId":101, ... "EmployeeDetails.EmployeeName":"Chris" ... }, ... { ... $set: { ... "EmployeeDetails.$.EmployeeName" : "Robert" ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo134.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Robert", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }