본문 바로가기
  • 삽질하는 자의 블로그
메인-프로젝트/Next.js - 심리검사와 강아지 프로젝트

8. MongDB의 쿼리조건 : [ 특정 string 포함 조건], [ or 과 and 의 조건]

by 이게뭐당가 2023. 2. 3.

MongDB 에 접근해 값을 가져올것이다.

 

1. 정 string 이 포함되어 있는 조건

2. 여러개의 특정 stiring 들 하나라도 포함되어 있다면 가져오는 조건

3. 특정 string 이 전부 포함되어야만 가져오는 조건

 

MongDB 의 매뉴얼을 보자

https://www.mongodb.com/docs/manual/reference/operator/query/regex/

 

$regex — MongoDB Manual

Docs Home → MongoDB Manual This page describes regular expression search capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB Atlas, MongoDB offers an improved full-text search solution, Atlas Search, which has its own $regex

www.mongodb.com

 

나도 사용해본다.

 

1. String 이 포함되어 있다면 만족 ( $regex )

$regex : "string"	// 혹은
$regex : /string/

DB의 값에 "string" 이라는 글자가 들어있다면 만족하므로

{ data : "is include string"}
{ data : "is not include sting"}

결과적으로

{ data : "is include string"}

해당 값이 가져와질것이다.

 

2. 하나라도 만족 ( $or ) 혹은 전부 만족 ( $and )

$and : [
    data:{"hi"}
    data:{"bye"}
]

-------------------------------------

$or : [
    data:{"hi"}
    data:{"bye"}
]

조건이 조금 이상하긴 하지만,

data:{"hi"} 이면서 data:{"bye"} 를 전부 만족            →  ( $and )

data:{"hi"}  혹은 data:{"bye"}  둘중 하나라도 만족   →   ( $or)

 

 

3. 따라서, 최종적으로 $regex 와 $or , $and 조건을 이용하여, MongoDB 의 값을 가져와보자.

 

req.body.personality 는 배열이다.

req.body.personality  안에는 [ "x", "y", "z"] 가 들어있다.

MongoDB 에서 Find 를 할때, "x" 혹은 "y" 혹은 "z" 가 하나라도 문자열에 포함되어 있다면 그 값을 가져올것이다.

< api / test.ts >

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    const dbName = "...";
    const collectionName = "...";

    const result = await client
        .db(dbName)
        .collection(collectionName)
        .find({
            $or: [		// $or 을 통해, 하나의 조건만 만족하더라도 선택
                { personality: { $regex: req.body.personality[0] } },	// $regex 를 통해, 해당값이 포함되어있다면 선택
                { personality: { $regex: req.body.personality[1] } },
            ],         
            size: req.body.size }).toArray();

};

 

조금더 세련되게 만들어보자.

 

.find({
    $or: req.body.personality.map((item: string) => ({
        personality: { $regex: item },
    })),
    size: req.body.size,
})

반복문을 통해, 깔끔하게 만들어보았다.

댓글