SQL vs MQL
SQL에 익숙한 사람은 SQL과 비교하여 학습하면 좀 더 MQP을 쉽게 이해할 것이라 생각합니다.
https://www.mongodb.com/docs/manual/reference/sql-comparison/
SQL to MongoDB Mapping Chart — MongoDB Manual
Docs Home → MongoDB Manual In addition to the charts that follow, you might want to consider the Frequently Asked Questions section for a selection of common questions about MongoDB.The following table presents the various SQL terminology and concepts an
www.mongodb.com
Operators
뒤에서 자세하게 설명하겠지만 MQL은 SQL의 where 같은 조건문을 첫 번째 줄에 작성해줍니다. 이때 이 문장을 Query Filter라 합니다. Query Filter에 대한 조건을 지정하기 위해 사용하는 것이 Operator입니다. (Operator가 조건 연산자로만 사용하는 것은 아닙니다.)
아래는 같지 않다라는 조건인 $ne입니다.
-- SQL
SELECT *
FROM people
WHERE status != "A"
-- MQL
db.people.find(
{ status: { $ne: "A"} }
)
이런 Operator를 전부 외워서 사용하기 어렵기 때문에 MongoDB Document를 참고하시기 바랍니다.
https://www.mongodb.com/docs/manual/reference/operator/
Operators — MongoDB Manual
Docs Home → MongoDB Manual To learn which operators are unsupported in MongoDB Atlas, see Unsupported Commands in Atlas.Query and Projection OperatorsQuery operators provide ways to locate data within the database and projection operators modify how data
www.mongodb.com
MongoDB Query 문법
기본적인 문법
# DB 확인
show dbs
# DB 이동
use db_name
# collection 확인
show collections
# collection 삭제
db.users.drop()
삽입
# When the collection exists: Data Insert
# When the collection doesn't exists: Table Create & Data Insert
db.users.insertOne({
name: "hong",
age: 30,
job: "Chef",
joinDate: new ISODate("2024-01-01"),
salary: 2000000,
yearWorked: 7
})
# Multiple Data Insert
db.users.insertMany([
{
name: "kim",
age: 21,
job: "Student",
joinDate: new ISODate("2016-03-09"),
withdrawalDate: newISODate("2017-02-09"),
yearWorked: null
},
{
name: "lee",
age: 28,
job: "Scientist",
joinDate: new ISODate("2019-11-09"),
salary: 3000000
}
])
- insertOne(): 데이터 삽입
- insertMany(): 여러 데이터 삽입, 2개 이상의 도큐먼트를 삽입할 때는 insertMany() 성능이 더 좋습니.
조회
- 조회 문법에서 첫 번째 인자에는 Query Filter가 들어갑니다.
- Operators('$')를 사용할 때 {}로 묶어서 사용합니다.
아래는 조회에 관한 간단한 예시입니다. 여러 조건에 대해 공부하고 싶다면 위에 Operators링크를 클릭해주면 됩니다.
# find all
db.users.find()
# find on conditions
db.users.find({
hasBonus: true,
yearWorked: { $lte: 5}
})
db.users.find({
$and: [
{ hasBonus: true },
{ yearWorked: { $lte: 5} }
]
})
- $and
Query Filter에서 기본적으로 쉼표를 구분자로 두면 and 연산자로 동작을 합니다. and 연산자를 명시하고 싶은 경우 $and를 사용하면 됩니다. 이때 배열로 하여 Query Filter 별로 묶어주어야 합니다.
수정
# updateOne
db.users.updateOne(
{ name: "kim" },
{
$set: {
salary: 2910000,
job: "Developer"
},
$unset: {
withdrawalDate: ""
}
}
)
# updateMany
db.users.updateMany(
{ withdrawalDate: { $exists: false }, joinDate: { $exists: true} },
{ $mul: {salary: Decimal128("1.05")} }
)
- $set: 데이터 수정
- $unset: 빈칸으로 지정하면, 필드가 제거됩니다.
- $exists: 필드가 존재하는지
- $mul: 곱하기 연산
삭제
# delete one
db.users.deleteOne({ name: "kim" })
# delete All
db.users.deleteMany({})
Mongosh Methods
mongodb와 상호작용 가능한 함수들로, DB 및 컬렉션을 유용하게 다룰 수 있습니다.
모든 mongosh method를 설명할 수 없기 때문에 document 링크를 첨부하도록 하겠습니다.
https://www.mongodb.com/docs/manual/reference/method/
mongosh Methods — MongoDB Manual
Docs Home → MongoDB Manual JavaScript in MongoDBAlthough these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.For details on a specific method, inclu
www.mongodb.com
1. db.collection.bulkWrite()
: Performs multiple write operations with controls for order of execution.
db.collection.bulkWrite(
[ <operation 1>, <operation 2>, ... ],
{
writeConcern : <document>,
ordered : <boolean>
}
)
예시)
db.bulk.bulkWrite(
[
{ insertOne: {doc: 1, order: 1}},
{ insertOne: {doc: 2, order: 2}},
{ insertOne: {doc: 3, order: 3}},
{ insertOne: {doc: 4, order: 4}},
{ insertOne: {doc: 3, order: 5}},
{
deleteOne: {
filter: {doc: 2}
}
},
{
updateOne: {
filter: {doc: 1},
update: {
$set: {doc: 5}
}
}
}
],
{ordered: true}
)
여러가지 쿼리들을 한 번에 날릴 수가 있습니다. 이때 ordered 옵션은 기본적으로 ture입니다. 이 옵션은 순차적으로 명령어가 실행되는 옵션이고, false로 지정한 경우 순서와 상관없이 성능 최적화 방향으로 수행되게 됩니다.
2. db.collection.countDocuments()
:컬렉션을 탐색하여 정확한 document 수를 반환합니다.
3. db.collection.estimatedDocumentCount()
:컬렉션을 탐색하지 않고 document 수의 근사치를 반환합니다. 대신 속도가 빠르기 때문에 대용량 컬렉션에서 document 수가 정확하지 않아도 되는 경우 사용합니다.
4. db.collection.distinct("컬럼")
:특정 필드에서 중복되지 않은 값들을 배열로 반환합니다.
5. ... mongosh methods document 링크 확인
'DBMS > MongoDB' 카테고리의 다른 글
MongoDB GROUP BY와 유사한 Aggregation (1) | 2024.01.31 |
---|---|
MongoDB 배열 다루는 문법 (1) | 2024.01.30 |
MongoDB MongoDB 배포 형태: Replica Set & Sharded Cluster (0) | 2024.01.25 |
MongoDB MongoDB: 문서 지향 NoSQL (0) | 2024.01.23 |