Database/monogodb

[MongoDB] ๊ฒŒ์‹œ๊ธ€ ์ฝ์Œ(read)/์•ˆ์ฝ์Œ(unread) ํ‘œ์‹œ ์ƒํƒœ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 2. 11. 21:42
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ์‹œ๊ฐ„์—๋Š” MongoDB ๋ชฝ๊ณ ๋””๋น„์—์„œ ๊ฒŒ์‹œ๊ธ€ ์ฝ์Œ(read)/์•ˆ์ฝ์Œ(unread) ํ‘œ์‹œ์ƒํƒœ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to do

์šฐ์„  ์ œ ์ƒํ™ฉ์˜ ๊ฒฝ์šฐ ๊ณต์ง€์‚ฌํ•ญ Collection(๊ฒŒ์‹œ๊ธ€ Collection๋ผ๊ณ  ๋ด๋„ ๋ฌด๋ฐฉ), ๊ทธ๋ฆฌ๊ณ  ์‚ฌ์šฉ์ž Collection์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.  

 

User 

user collection์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. _id, userId, userName ํ•„๋“œ๋ฅผ ๊ฐ–๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

{
    _id: user_uniqueId,
    userId: senderId,
    userName: userName
}

 

Notice

notice collection์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. _id, noticeId, title, contents ํ•„๋“œ๋ฅผ ๊ฐ–๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

{
    _id: user_uniqueId,
    noticeId: noticeId,
    title: 'this is title',
    contents: 'this is the notice',
}

์œ„ ์ƒํ™ฉ์—์„œ ์ฝ์Œ/์•ˆ์ฝ์Œ ํ‘œ์‹œ ์ƒํƒœ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ํฌ๊ฒŒ 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ•ด๋ดค๋Š”๋ฐ์š”,

 

1. ์ƒˆ๋กœ์šด ์ฝ์Œ/์•ˆ์ฝ์Œ ํ‘œ์‹œ ์ƒํƒœ๋ฅผ ์œ„ํ•ด ์ƒˆ๋กœ์šด ์ปฌ๋ ‰์…˜์„ ๋งŒ๋“ค์–ด์„œ ๊ด€๋ฆฌ

{
    _id: notice_uniqueId,
    type: 'notice',
    userId: userId,
    noticeId: noticeId,
    read: true / false,
},
{
    _id: message_uniqueId,
    type: 'message',
    userId: userId,
    messageId: messageId,
    read: true / false,
}

 

2. notice collection์— read_by ์™€ ๊ฐ™์€ ์ฝ์Œ/์•ˆ์ฝ์Œ ํ‘œ์‹œ ์ƒํƒœ ํŒ๋ณ„์„ ์œ„ํ•œ ํ•„๋“œ๋ฅผ ์ถ”๊ฐ€

{
    _id: 'document#42',
    ...
    read_by: ['admin', 'user1']
}

2๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์ค‘ ๊ณ ๋ฏผ์„ ํ•˜๋‹ค๊ฐ€ read_by ํ•„๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” ์ƒˆ๋กœ์šด ์ปฌ๋ ‰์…˜์„ ๋งŒ๋“œ๋Š” ๊ฒŒ ๋‚˜์„ ๊ฒƒ ๊ฐ™์•„ ์ฒซ๋ฒˆ์งธ ๋ฐฉ๋ฒ•์„ ํƒํ•˜๊ธฐ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค. read_byํ•„๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์„œ๋น„์Šค๋ฅผ ์ด์šฉํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ๋Š˜์–ด๋‚  ์ˆ˜๋ก ๊ฐ’์ด ๊ธฐํ•˜๊ธ‰์ˆ˜์ ์œผ๋กœ ๋Š˜์–ด๋‚  ๊ฒƒ ๊ฐ™์•˜๊ณ , ๋ถ„๋ฆฌ๋œ ์ƒํƒœ๋กœ ์ปฌ๋ ‰์…˜์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒŒ ํ†ต์ƒ์ ์œผ๋กœ ๋” ๋‚˜์€ ๋ฐฉ๋ฒ•์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. 

 

Create New Collection

์ฝ์Œ/์•ˆ์ฝ์Œ ํ‘œ์‹œ ์ƒํƒœ ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•œ ์ƒˆ๋กœ์šด ์ปฌ๋ ‰์…˜์„ ์ƒ์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค.  ์‚ฌ์šฉ์ž๊ฐ€ ํ•ด๋‹น notice Id ๋ฅผ ํด๋ฆญ ์‹œ, ๋งŒ๋“ค์–ด์ง„ ์ƒˆ๋กœ์šด ์ปฌ๋ ‰์…˜์— document ๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

์ปฌ๋ ‰์…˜์— ํ•ด๋‹นํ•˜๋Š” noticeId์™€ userId๊ฐ€ ์กด์žฌํ•  ๊ฒฝ์šฐ ์ด๋ฏธ ์ฝ์€ ๊ณต์ง€์‚ฌํ•ญ์ด ๋˜๊ฒ ์ฃ . ์•„๋ž˜์˜ ์ฟผ๋ฆฌ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ฝ์Œ/์•ˆ์ฝ์Œ ํ‘œ์‹œ ์ƒํƒœ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

db.read.find({type: 'notice', userId: userId, noticeId: noticeId })

 

 

 

 


https://stackoverflow.com/questions/4180817/mongodb-nosql-best-approach-to-handling-read-unread-status-on-messages

๋ฐ˜์‘ํ˜•