> db.movies.insertOne({'title': '엘리멘탈'})
_id를 따로 입력 해 주지 않았으므로 _id 자동 생성bulk_insert와 비슷
> db.movides.insertMany([
{'title': '엘리멘탈'},
{'title': '오펜하이머'},
...
])
>> {
acknowledged: true,
insertedIds: {
'0': ObjectId("64eafa5d96a5c1d4ab0b5c36"),
'1': ObjectId("64eafa5d96a5c1d4ab0b5c37")
}
}
> db.movies.find()
[
{ _id: ObjectId("64eafa5d96a5c1d4ab0b5c36"), title: '엘리멘탈' },
{ _id: ObjectId("64eafa5d96a5c1d4ab0b5c37"), title: '오펜하이머' }
]
ordered에 true로 지정하면 된다.(default) - 정렬 연산ordered에 false로 지정하면 된다.(default) - 비정렬 연산> db.movies.insertMany([
{'_id':1, 'title': '엘리멘탈' },
{'_id':1, 'title': '오펜하이머'},
{'_id': 3, 'title': '미션임파서블'}
])
// duplicate 에러 발생
>> Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: practice.movides index: _id_ dup key: { _id: 1 }
Result: BulkWriteResult {
**insertedCount: 1,**
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': 1, '1': 1, '2': 3 }
}
Write Errors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: practice.movides index: _id_ dup key: { _id: 1 }',
errInfo: undefined,
op: { _id: 1, title: '오펜하이머' }
}
}
]
> db.movies.find()
// _id: 1 만 삽입 성공
>>[ { _id: 1, title: '엘리멘탈' } ]> db.movides.insertMany([
{'_id':1, 'title': '엘리멘탈'},
{'_id':1, 'title': '오펜하이머'},
{'_id': 3, 'title': '미션임파서블'}
],
{'ordered':false}
)
// duplicate 에러 발생
>> Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: practice.movides index: _id_ dup key: { _id: 1 }
Result: BulkWriteResult {
**insertedCount: 2,**
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': 1, '1': 1, '2': 3 }
}
Write Errors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: practice.movides index: _id_ dup key: { _id: 1 }',
errInfo: undefined,
op: { _id: 1, title: '오펜하이머' }
}
}
]
> db.movies.find()
// _id: 1, 3 성공
>> [ { _id: 1, title: '엘리멘탈' }, { _id: 3, title: '미션임파서블' } ]_id 필드 유/무 확인> db.movides.insert({'title': '엘리멘탈' })
// Warning
>> DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
// insert 정상 작동
{
acknowledged: true,
insertedIds: { '0': ObjectId("64eb0ab3d89754f67e60ae00") }
}
> db.movies.find()
>> [
{ _id: 1, title: '엘리멘탈', month: 7 },
{ _id: 2, title: '오펜하이머', month: 7 },
{ _id: 3, title: '미션임파서블', month: 6 }
]
> db.movies.deleteOne({'_id':1})
>> { acknowledged: true, deletedCount: 1 }
> db.movies.find()
>> [
{ _id: 2, title: '오펜하이머', month: 7 },
{ _id: 3, title: '미션임파서블', month: 6 }
]
===
> db.movies.find()
>> [
{ _id: 1, title: '엘리멘탈', month: 7 },
{ _id: 2, title: '오펜하이머', month: 7 },
{ _id: 3, title: '미션임파서블', month: 6 }
]
// month 7인 도큐먼트가 2개지만 deleteOne은 1개만 삭제
> db.movies.deleteOne({'month': 7})
>> { acknowledged: true, deletedCount: 1 }
> db.movies.find()
>> [
{ _id: 2, title: '오펜하이머', month: 7 },
{ _id: 3, title: '미션임파서블', month: 6 }
]> db.movies.find()
>> [
{ _id: 1, title: '엘리멘탈', month: 7 },
{ _id: 2, title: '오펜하이머', month: 7 },
{ _id: 3, title: '미션임파서블', month: 6 }
]
> db.movies.deleteMany({'month':7})
>> { acknowledged: true, deletedCount: 2 }
> db.movies.find()
>> [ { _id: 3, title: '미션임파서블', month: 6 } ]remove 메소드 사용remove 지원되지만 Warning 발생updateOne('filter document', 'modifier document')
updateMany('filter document', 'modifier document')db.movies.find()
[ { _id: 3, title: '엘리멘탈', month: 3 } ] > db.movies.find()
>> [ { _id: 3, title: '미션임파서블', month: 6 } ]
> db.movies.replaceOne({'_id': 3}, {'title': '엘리멘탈'})
>> {
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈' } ]update
$inc - 값 증가/감소 연산자 (+, -)
int, long, double, decimal 타입 값만 사용 가능
null, bool, str 사용 불가
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈', open: { month: 3 } } ]
> db.movies.updateOne({"title":"엘리멘탈"},{"$inc":{"views": 1}})
> db.movies.find()
[ { _id: 3, title: '엘리멘탈', open: { month: 3 }, views: 1 } ]
---------------------------------------------------------------------
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈', month: 3, views: 3 } ]
> db.movies.update({"title":"엘리멘탈"},{"$inc":{"views":1}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈', month: 3, views: 4 } ]
---------------------------------------------------------------------
> db.movies.find()
[ { _id: 3, title: '엘리멘탈', open: { month: 3 }, views: 4 } ]
> db.movies.updateOne({"title":"엘리멘탈"},{"$inc":{"views": -2}})
> db.movies.find()
[ { _id: 3, title: '엘리멘탈', open: { month: 3 }, views: 2 } ]
$set - 데이터 추가 및 수정
> db.movies.find()
>>[ { _id: 3, title: '엘리멘탈', month: 3, views: 4 } ]
> db.movies.updateOne({"title":"엘리멘탈"},{"$set":{"month":9}})
>> {
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈', month: 9, views: 4 } ]
$unset - key, value 제거
> db.movies.find()
>>[ { _id: 3, title: '엘리멘탈', month: 9, views: 4 } ]
> db.movies.updateOne({"title":"엘리멘탈"},{"$unset":{"month": 1}})
>>{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
> db.movies.find()
>> [ { _id: 3, title: '엘리멘탈', views: 4 } ]
$push - 배열에 쌓는 연산자
> db.movies.find()
>> [
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [ { contents: '재미x' } ]
}
]
> db.movies.updateOne({"title":"엘리멘탈"},{"$push":{"comment":{"contents":"재미o"}}})
> db.movies.find()
>> [
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [ { contents: '재미x' }, { contents: '재미o' } ]
}
]
---------------------------------------------------------------------------
db.movies.find()
[
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [ { contents: '재미x' }, { contents: '재미o' } ]
}
]
> db.movies.updateOne({"title":"엘리멘탈"},{"$push":{"comment":{"$each":[{"contents":"재미o"},{"contents":"재밍미징"}]}}})
> db.movies.find()
[
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [
{ contents: '재미x' },
{ contents: '재미o' },
{ contents: '재미o' },
{ contents: '재밍미징' }
]
}
]
> db.movies.updateOne({"title":"엘리멘탈"},{"$push":{"comment":{"$each":[{"contents":"재미o"},{"contents":"재밍미징"}], "$slice": -5}}})
// 5개 이상 X
> db.movies.find()
[
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [
{ contents: '재미o' },
{ contents: '재미o' },
{ contents: '재밍미징' },
{ contents: '재미o' },
{ contents: '재밍미징' }
]
}
]
$slice로 최대 저장 개수 제한 가능
$slice나 $sort를 $push와 함께 사용하려면 $each도 함께 사용해야 한다.
$addToSet - 중복 값 추가 X
> db.User.find()
[
{
_id: ObjectId("638deb3234a057cad223a0ce"),
name: 'Jaemon',
email: [ 'ajbj@naver.com', 'abc@naver.com', 'ddd@naver.com' ]
}
]
> db.User.updateOne({"name":"Jaemon"}, {"$addToSet": {"email":"abc@naver.com"}})
> db.User.find()
[
{
_id: ObjectId("638deb3234a057cad223a0ce"),
name: 'Jaemon',
email: [ 'ajbj@naver.com', 'abc@naver.com', 'ddd@naver.com' ]
}
]
> db.User.updateOne({"name":"Jaemon"}, {"$addToSet": {"email":"abc1@naver.com"}})
> db.User.find()
[
{
_id: ObjectId("638deb3234a057cad223a0ce"),
name: 'Jaemon',
email: [
'ajbj@naver.com',
'abc@naver.com',
'ddd@naver.com',
'abc1@naver.com'
]
}
]
요소 제거하기
배열의 위치 기반 변경
> db.movies.find()
>> [
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [
{ contents: '재미o', views: 5 },
{ contents: '재미o', views: 3 },
{ contents: '재밍미징', views: 1},
{ contents: '재미o', views: 2 },
{ contents: '재밍미징', views: 6 }
]
}
]
> db.movies.updateOne({"title":"엘리멘탈"}, {"$inc": {"comment.0.views": 1}})
ㄴ index부분만 증가
> db.movies.find()
[
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [
{ contents: '재미o', views: 6 },
{ contents: '재미o', views: 3 },
{ contents: '재밍미징', views: 1 },
{ contents: '재미o', views: 2 },
{ contents: '재밍미징', views: 6 }
]
}
]db.movies.updateOne({"title":"엘리멘탈1"}, {"$inc": {"comment.2.views": 1}})
{
acknowledged: true,
insertedId: null,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 0
}
------------------------------------------------------------------------
> db.movies.updateOne({"title":"엘리멘탈2"}, {"$inc": {"comment.views": 1}}, {"upsert": true})
[
{
_id: 3,
title: '엘리멘탈',
open: { month: 3 },
views: 2,
comment: [
{ contents: '재미o', views: 6 },
{ contents: '재미o', views: 3 },
{ contents: '재밍미징', views: 1 },
{ contents: '재미o', views: 3 },
{ contents: '재밍미징', views: 6 }
]
},
{
_id: ObjectId("64ff12a20803fe720ebca357"),
title: '엘리멘탈2',
comment: { views: 1 }
}$setOnInsert
저장 셀 보조자
다중 도큐먼트 갱신
.... # before
update_result = client.admin_member.update_one({'_id': obj['_id']}, {'$set': params})
if is_return:
return client.admin_member.find_one({'_id': obj['_id']})
return update_result
vs
.... # after
return client.admin_member.find_one_and_update({'_id': obj['_id']}, {'$set': params}, return_document=True)
# find_one_and_update
# returnNewDocument 없으면 update 이전 값 반환
# returnNewDocument로 update 이후 값을 반환 replace 동일