Framework/Springboot

[Springboot] ์Šคํ”„๋ง๋ถ€ํŠธ + ๋ชฝ๊ณ (mongo)์—์„œ OR ์ฟผ๋ฆฌ query ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• (+ Criteria)

yuri lee 2023. 2. 12. 10:11
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” ์Šคํ”„๋ง๋ถ€ํŠธ + ๋ชฝ๊ณ (mongo)์—์„œ OR ์ฟผ๋ฆฌ query ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to do

Criteria API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("A").is(10),Criteria.where("B").is(20));
Query query = new Query(criteria);

mongoOps.find(query, <Yourclass>.class, "collectionName");

 

+) ์ฐธ๊ณ ๋กœ Criteria ์€  ๊ธฐ์ค€๊ฐ’์ด๋ผ๋Š” ์˜๋ฏธํž™๋‹ˆ๋‹ค. find ๋ฉ”์†Œ๋“œ ์•ˆ์—์„œ { age: { $gt: 18 } } ์™€ ๊ฐ™์€ ์กฐ๊ฑด๋ฌธ์„ ์ž…๋ ฅํ•˜๋Š” ๋ถ€๋ถ„์„ ๋œปํ•ฉ๋‹ˆ๋‹ค.

db.users.find( // collecrtion
    { age: { $gt: 18 } }, // query criteria
    { name: 1, address: 1 } // projection
).limnit(5)

 


https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/query/Criteria.html

https://stackoverflow.com/questions/16478101/spring-data-mongo-use-or-in-query

๋ฐ˜์‘ํ˜•