다른 NoSQL에서 찾아보기 힘든 장정미다.
인스타그램에서 게시물을 올릴 때 필요한 정보는 다음과 같다.
{
_id: POST_ID, title: POST_TITLE,
content: POST_CONTENT,
author: POST_WRITER,
hashtags: [ TAG1, TAG2, TAG3 ], // subdocument
time: POST_TIME
comments: [ // subdocument
{
username: COMMENT_WRITER,
mesage: COMMENT_MESSAGE,
time: COMMENT_TIME
},
{
username: COMMENT_WRITER,
mesage: COMMENT_MESSAGE,
time: COMMENT_TIME
}
]
}
한 쌍 이상의 Key 와 value가 pair 로 이루어진
Document들이 모여 Collection 을 이루고,
Collection 들은 Database 안에 포함 되어 있다.
그리고 Database 는 Server 안에 위치한다
일반적으로 JSON은 JavaScript Object Notation의 줄임말로 Javascript 언어의 일부로 정의되어있는 형식이며 2013년에 공식화 된 형식이다.
JSON의 형태는 일반적으로 key와 value의 값으로 채워져 있다.
직관적이고 간단한 특성으로 쉽게 이해할 수 있는 형태의 표현 방법
{
"_id": "10009999",
"listing_url": "https://www.aaabbb.com/rooms/10009999",
"name": "Horto flat with small garden",
"summary": "One bedroom + sofa-bed ...",
"cancellation_policy": "flexible",
"last_scraped": {
"$date": {
"$numberLong": "1549861200000"
}
}
}
BSON은 단순히 말하면 Binary JSON이다.
JSON과 동일한 구조지만 Binary 형태로 변경된 구조를 말한다.
그럼 JSON이 있는데 왜 BSON이 등장한 것일까?
몽고DB가 처음 개발될 때에는 JSON을 이용해서 개발을 진행했다고 한다. 그러다가 문제점 몇가지가 나타나기 시작한 것이다.
이 외에도 여러가지 문제가 발생하여 고안해 낸것이 바로 BJSON 인 것이다.
JSON구조의 좋은점은 그대로 가져가면서 기계가 빠르게 읽을 수 있는 binary 형태로 변경하여 저장을 한 것이다.
동일한 형태로 사람에게 보여질 때에는 JSON의 형태로 보여주고, 저장할 때나 네트워크로 전송할 때에는 BSON 형태로 만들어서 저장 또는 전송한다.
{"hello": "world"}
→ \x16\x00\x00\x00 // total document size
\x02 // 0x02 = type String
hello\x00 // field name
\x06\x00\x00\x00world\x00 // field value
\x00 // 0x00 = type EOO ('end of object')
MONGODB 정리 - NoSQL & mongoDB 주종면
[MONGO] 📚 몽고디비 특징 & 비교 & 구조 (NoSQL)
[db.collection.insertOne()](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/#mongodb-method-db.collection.insertOne)
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
[db.collection.insertMany()](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/#mongodb-method-db.collection.insertMany)
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
다음 메서드는 컬렉션에 새 문서를 추가할 수도 있습니다.
[db.collection.updateOne()](https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/#mongodb-method-db.collection.updateOne)
옵션 과 함께 사용할 때 upsert: true
.[db.collection.updateMany()](https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#mongodb-method-db.collection.updateMany)
옵션 과 함께 사용할 때 upsert: true
.[db.collection.findAndModify()](https://www.mongodb.com/docs/manual/reference/method/db.collection.findAndModify/#mongodb-method-db.collection.findAndModify)
옵션 과 함께 사용할 때 upsert: true
.[db.collection.findOneAndUpdate()](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/#mongodb-method-db.collection.findOneAndUpdate)
옵션 과 함께 사용할 때 upsert: true
.[db.collection.findOneAndReplace()](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace/#mongodb-method-db.collection.findOneAndReplace)
옵션 과 함께 사용할 때 upsert: true
.[db.collection.bulkWrite()](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/#mongodb-method-db.collection.bulkWrite)
.db.inventory.find( {} )
## sql
## SELECT * FROM inventory
이름 | 설명 |
---|---|
$eq | 지정된 값과 같은 값을 찾습니다. |
$gt | 지정된 값보다 큰 값과 일치합니다. |
$gte | 지정된 값보다 크거나 같은 값을 찾습니다. |
$in | 배열에 지정된 값 중 하나와 일치합니다. |
$lt | 지정된 값보다 작은 값과 일치합니다. |
$lte | 지정된 값보다 작거나 같은 값을 찾습니다. |
$ne | 지정된 값과 같지 않은 모든 값과 일치합니다. |
$nin | 배열에 지정된 값과 일치하지 않습니다. |
db.inventory.find( { status: "D" } )
## sql
## **SELECT * FROM inventory WHERE status = "D"**
AND
조건 지정db.inventory.find( { status: "A", qty: { $lt: 30 } } )
## sql
## SELECT * FROM inventory WHERE status = "A" AND qty < 30
OR
조건 지정db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
## sql
## SELECT * FROM inventory WHERE status = "A" OR qty < 30
AND
뿐만 아니라 지정OR
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
## sql
## SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
포함/중첩 문서의 필드에 쿼리 조건을 지정하려면 다음을 사용하십시오.점 표기법( "field.nestedField"
).
점 표기법을 사용하여 쿼리할 때 필드와 중첩 필드는 따옴표 안에 있어야 합니다.
db.inventory.find( { "size.uom": "in" } )
배열에 같음 조건을 지정하려면 요소의 순서를 포함하여 일치시킬 정확한 배열이 있는 쿼리 문서를 사용합니다 { <field>: <value> }
.<value>
다음 예제는 필드 tags
값이 정확히 두 개의 요소 "red"
와 "blank"
, 지정된 순서로 포함된 배열인 모든 문서를 쿼리
db.inventory.find( { tags: ["red", "blank"] } )
배열의 순서나 다른 요소에 관계없이 요소 "red"
와 "blank"
모두를 포함하는 배열을 찾으려면
요소가 하나이상 포함되어 있는지 쿼리하려면 가 요소 값인 필터 를 사용
db.inventory.find( { tags: "red" } )
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
다음 예에서는 instock
배열의 요소가 지정된 문서와 일치하는 모든 문서를 선택
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
배열에 중첩된 문서의 인덱스 위치를 모르는 경우 배열 필드의 이름을 점( .
)으로 연결하고 중첩된 문서의 필드 이름을 연결
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
값이 다음보다 작거나 같은 instock
필드가 포함된 문서를 배열의 첫 번째 요소로 포함하는 모든 문서를 선택
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
사용$elemMatch연산자를 사용하여
하나 이상의 포함된 문서가 지정된 모든 기준을 충족하도록 포함된 문서의 배열에 여러 기준을 지정
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
배열에 크 거나 작거나 같은 instock
필드가 포함된 문서가 하나 이상 있는 문서를 쿼리합니다 .qty1020
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
포함된 문서의 특정 필드를 반환할 수 있습니다. 사용 점 표기법포함된 필드를 참조 1
하고 투영 문서에서 로 설정합니다.
다음 예제는 다음을 반환합니다.
_id
기본적으로 반환됨),item
필드 ,status
필드 ,uom
필드입니다 size
.uom
필드는 size
문서 에 포함 된 상태로 유지
db.inventory.find( { status: "A" } )
## sql
SELECT * from inventory WHERE status = "A"
item
, status
, **_id
필드만 반환db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
## sql
SELECT _id, item, status from inventory WHERE status = "A"
**_id
필드 억제
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
## sql
SELECT item, status from inventory WHERE status = "A"
**제외된 필드를 제외한 모든 필드 반환**
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )
쿼리 는 값이 있는 필드를 포함 하거나 포함 하지 않는 { item : null }
문서와 일치 합니다.itemnull
item
db.inventory.find( { item: null } )
{ item : { $type: 10 } }
쿼리 는 값이 인 필드가 포함된 문서 만 일치시킵니다 . 즉, 필드의 값은 itemnullitem
BSON 유형 Null
(유형 번호 10
) :
db.inventory.find( { item : { $type: 10 } } )
다음 예제에서는 필드가 포함되지 않은 문서를 쿼리
쿼리 는 필드 { item : { $exists: false } }
가 포함되지 않은 문서와 일치
db.inventory.find( { item : { $exists: false } } )
처음 자료 insert
db.students.insertMany( [
{ _id: 1, test1: 95, test2: 92, test3: 90, modified: new Date("01/05/2020") },
{ _id: 2, test1: 98, test2: 100, test3: 102, modified: new Date("01/05/2020") },
{ _id: 3, test1: 95, test2: 110, modified: new Date("01/04/2020") }
] )
**db.students.updateOne( { _id: 3 }, [ { $set: { "test3": 98, modified: "$$NOW"} } ] )**
생성 자료
db.students2.insertMany( [
{ "_id" : 1, quiz1: 8, test2: 100, quiz2: 9, modified: new Date("01/05/2020") },
{ "_id" : 2, quiz2: 5, test1: 80, test2: 89, modified: new Date("01/05/2020") },
] )
db.students2.updateMany( {},
[
{ $replaceRoot: { newRoot:
{ $mergeObjects: [ { quiz1: 0, quiz2: 0, test1: 0, test2: 0 }, "$$ROOT" ] }
} },
{ $set: { modified: "$$NOW"} }
]
)
비교
{
_id: new Int32(2),
quiz2: new Int32(5),
test1: new Int32(80),
test2: new Int32(89),
modified: 2020-01-04T15:00:00.000Z
}
{
_id: new Int32(1),
quiz1: new Int32(8),
test2: new Int32(100),
quiz2: new Int32(9),
modified: 2020-01-04T15:00:00.000Z
}
{
_id: new Int32(2),
quiz1: new Int32(0),
quiz2: new Int32(5),
test1: new Int32(80),
test2: new Int32(89),
modified: 2022-09-09T12:14:23.954Z
}
{
_id: new Int32(1),
quiz1: new Int32(8),
quiz2: new Int32(9),
test1: new Int32(0),
test2: new Int32(100),
modified: 2022-09-09T12:14:23.954Z
}
db.students3.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "modified" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "modified" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "modified" : ISODate("2019-01-01T00:00:00Z") }
] );
집계 파이프라인을 사용하여 계산된 등급 평균 및 문자 등급으로 문서를 업데이트
db.students3.updateMany(
{ },
[
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] }, modified: "$$NOW" } },
{ $set: { grade: { $switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
} } } }
]
)
비교
{
_id: new Int32(1),
tests: [ new Int32(95), new Int32(92), new Int32(90) ],
modified: 2019-01-01T00:00:00.000Z
}
{
_id: new Int32(2),
tests: [ new Int32(94), new Int32(88), new Int32(90) ],
modified: 2019-01-01T00:00:00.000Z
}
{
_id: new Int32(3),
tests: [ new Int32(70), new Int32(75), new Int32(82) ],
modified: 2019-01-01T00:00:00.000Z
}
{
_id: new Int32(1),
tests: [ new Int32(95), new Int32(92), new Int32(90) ],
modified: 2022-09-09T12:21:57.406Z,
average: new Double(92.0),
grade: 'A'
}
{
_id: new Int32(2),
tests: [ new Int32(94), new Int32(88), new Int32(90) ],
modified: 2022-09-09T12:21:57.406Z,
average: new Double(90.0),
grade: 'A'
}
{
_id: new Int32(3),
tests: [ new Int32(70), new Int32(75), new Int32(82) ],
modified: 2022-09-09T12:21:57.406Z,
average: new Double(75.0),
grade: 'C'
}
db.students4.insertMany( [
{ "_id" : 1, "quizzes" : [ 4, 6, 7 ] },
{ "_id" : 2, "quizzes" : [ 5 ] },
{ "_id" : 3, "quizzes" : [ 10, 10, 10 ] }
] )
집계 파이프라인을 사용하여 다음을 사용하여 문서에 퀴즈 점수를 추가
db.students4.updateOne( { _id: 2 },
[ { $set: { quizzes: { $concatArrays: [ "$quizzes", [ 8, 6 ] ] } } } ]
)
비교
{
_id: new Int32(1),
quizzes: [ new Int32(4), new Int32(6), new Int32(7) ]
}
{ _id: new Int32(2), quizzes: [ new Int32(5) ] }
{
_id: new Int32(3),
quizzes: [ new Int32(10), new Int32(10), new Int32(10) ]
}
{
_id: new Int32(1),
quizzes: [ new Int32(4), new Int32(6), new Int32(7) ]
}
{
_id: new Int32(2),
quizzes: [ new Int32(5), new Int32(8), new Int32(6) ]
}
{
_id: new Int32(3),
quizzes: [ new Int32(10), new Int32(10), new Int32(10) ]
}
temperatures
컬렉션 생성db.temperatures.insertMany( [
{ "_id" : 1, "date" : ISODate("2019-06-23"), "tempsC" : [ 4, 12, 17 ] },
{ "_id" : 2, "date" : ISODate("2019-07-07"), "tempsC" : [ 14, 24, 11 ] },
{ "_id" : 3, "date" : ISODate("2019-10-30"), "tempsC" : [ 18, 6, 8 ] }
] )
db.temperatures.updateMany( { },
[
{ $addFields: { "tempsF": {
$map: {
input: "$tempsC",
as: "celsius",
in: { $add: [ { $multiply: ["$$celsius", 9/5 ] }, 32 ] }
}
} } }
]
)
비교
{
_id: new Int32(1),
date: 2019-06-23T00:00:00.000Z,
tempsC: [ new Int32(4), new Int32(12), new Int32(17) ]
}
{
_id: new Int32(2),
date: 2019-07-07T00:00:00.000Z,
tempsC: [ new Int32(14), new Int32(24), new Int32(11) ]
}
{
_id: new Int32(3),
date: 2019-10-30T00:00:00.000Z,
tempsC: [ new Int32(18), new Int32(6), new Int32(8) ]
}
{
_id: new Int32(1),
date: 2019-06-23T00:00:00.000Z,
tempsC: [ new Int32(4), new Int32(12), new Int32(17) ],
tempsF: [ new Double(39.2), new Double(53.6), new Double(62.6) ]
}
{
_id: new Int32(2),
date: 2019-07-07T00:00:00.000Z,
tempsC: [ new Int32(14), new Int32(24), new Int32(11) ],
tempsF: [ new Double(57.2), new Double(75.2), new Double(51.8) ]
}
{
_id: new Int32(3),
date: 2019-10-30T00:00:00.000Z,
tempsC: [ new Int32(18), new Int32(6), new Int32(8) ],
tempsF: [ new Double(64.4), new Double(42.8), new Double(46.4) ]
}
db.collection.updateOne() | 여러 문서가 지정된 필터와 일치하더라도 지정된 필터와 일치하는 단일 문서만 업데이트합니다. |
---|---|
db.collection.updateMany() | 지정된 필터와 일치하는 모든 문서를 업데이트합니다. |
db.collection.replaceOne() | 여러 문서가 지정된 필터와 일치하더라도 지정된 필터와 일치하는 최대 단일 문서를 바꿉니다. |
db.inventory.deleteMany({})
db.inventory.deleteMany({ status : "A" })