Database/monogodb

[MongoDB] ์˜ค๋ฆ„์ฐจ์ˆœ(Ascending)๊ณผ ๋‚ด๋ฆผ์ฐจ์ˆœ(Descending)์˜ ์˜๋ฏธ, ๋ชฝ๊ณ ๋””๋น„์—์„œ ์ •๋ ฌ sort ํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 1. 14. 23:48
๋ฐ˜์‘ํ˜•

Intro 

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” MongoDB ๋ชฝ๊ณ ๋””๋น„์—์„œ ์ฟผ๋ฆฌ๋ฅผ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ์šฐ์„  ๊ทธ์— ์•ž์„œ ์˜ค๋ฆ„์ฐจ์ˆœ๊ณผ ๋‚ด๋ฆผ์ฐจ์ˆœ์˜ ์˜๋ฏธ์— ๋Œ€ํ•ด ํ•จ๊ป˜ ์‚ดํŽด๋ณด๋„๋ก ํ•ด์š”. 

 

Ascending / ์˜ค๋ฆ„์ฐจ์ˆœ

์˜ค๋ฆ„์ฐจ์ˆœ (Ascending)์€ smallest to largest ๋กœ, ์ž‘์€ ์ˆซ์ž์—์„œ ํฐ ์ˆซ์ž๋กœ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. (ex. 1 -> 2 -> 3 -> 4 -> 5)

 

Descending / ๋‚ด๋ฆผ์ฐจ์ˆœ

๋‚ด๋ฆผ์ฐจ์ˆœ (Descending)์€ largest to smallest๋กœ, ํฐ ์ˆซ์ž์—์„œ ์ž‘์€ ์ˆซ์ž๋กœ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.  (ex. 5 -> 4 -> 3 -> 2 -> 1)

 

How to sort in MongoDB

MongoDB์—์„œ 1์€ ์˜ค๋ฆ„์ฐจ์ˆœ, -1์€ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์— ํ•ด๋‹นํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์•„๋ž˜์™€ ๊ฐ™์€ BSON ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. ์ฐธ๊ณ ๋กœ MongoDB๋Š” ์Šคํ‚ค๋งˆ๊ฐ€ ๊ณ ์ •๋œ ๊ตฌ์กฐ ๋Œ€์‹  JSON ํ˜•ํƒœ์˜ ๋™์  ์Šคํ‚ค๋งˆํ˜• ๋ฌธ์„œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ BSON์ด๋ผ๊ณ  ๋ถ€๋ฆ…๋‹ˆ๋‹ค. 

  {
    "key": 1,
    "username": "Liam",
    "age" : 20
  },
  {
    "key": 2,
    "username": "Noah",
    "age" : 24
  },
  {
    "key": 3,
    "username": "Oliver",
    "age" : 16
  },
  {
    "key": 4,
    "username": "William",
    "age" : 36
  },
  {
    "key": 5,
    "username": "Mason",
    "age" : 40
  },

 

# 1. ์˜ค๋ฆ„์ฐจ์ˆœ (asc)

age๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์„ ํ•˜๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ ์•„๋ž˜์˜ ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. 

db.collection.find().sort({"age": 1})

 

# 2. ๋‚ด๋ฆผ์ฐจ์ˆœ (desc)

age๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์„ ํ•˜๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ ์•„๋ž˜์˜ ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. 

db.collection.find().sort({"age": -1})
๋ฐ˜์‘ํ˜•