개발 일기

mongoose query builder ? 본문

서버/Node.js

mongoose query builder ?

이건욱

where

조건을 어떤 필드에 대해서 할것인지에 정할수가 있습니다.

 

Post.find().where('message')

 

equals , ne

equals = 일치 조건

ne = 일치 하지 않을 조건

 

Post.find().where('message').equals('gunwook')
Post.find().equals('message', 'gunwook') // 위와 동일한 쿼리
Post.find().ne('message', 'gunwook')

gt, lt, gte, lte

gt = 초과

lt = 미만

gte = 이상

lte = 이하

 

Post.find().where('id').gt(10)
Post.find().gt('id', 10);

in, nin, all

in = 어떠한 배열에 대해서 하나라도 일치하는지 여부

nin = 어떠한 배열에 대해서 하나라도 일치가 안되는지 여부

all = 어떠한 배열에 대해서 모두 다 일치하는지 여부

 

Post.find().where('message').in(['gunwook', 'temp'])
Post.find().in('message', ['gunwook', 'temp'])

and, or, nor

and = 모든 조건 만족 여부

or =  일부 조건 만족 여부

nor = 모두 다 만족 하지 않는지 여부

 

Post.find().all([{ name: 'gunwook' }, { id: 1 }]); 
Post.find().or([{ name: 'gunwook' }, { id: 1 }]); 

select

특정 필드만 가져올수가 있습니다. MongoDB 특성상 _id를 빼지 않는 이상 기본 출력됩니다.

빼는 방법은 1 or -1 을 지정할수도 있고 혹은 - 을 통해서도 할수가 있습니다.

 

Post.findOne().select('message') // { _id: ~, message: ~ }
Post.findOne().select('-_id message') // { message: ~ }
Post.findOne().select({ _id: 0 , message: 1 }) // { message: ~ }

skip, limit

skip = 해당 개수만큼 넘어 갈수가 있습니다.

limit = 개수 제한을 정할수가 있습니다.

 

ChatModel
  .find()
  .skip(offset * limit).limit(limit)
  .where(Parameter.ROOM_ID)
  .equals(roomId))

sort

정렬을 진행을 할때 사용할수가 있습니다.

기본적으로 asc (오름차순) 이고 1 과 -1 로 표현이 가능합니다.

 

Post.find().sort('-id or id'); // id 정렬
Post.find().sort({ id: 1, message: -1 });  
Post.find().sort({ id: 'asc', message: 'desc' });
Post.find().sort({ id: 'ascending', message: 'descending' });

 

distinct

지정한 필드에서 중복된 값을 제거후에 가져올 수가 있습니다.

 

Post.find().distinct('message')

regex

정규 표현식에 대해서 일치하는 조건만 가져올수가 있습니다.

Post.find().where('message').regex(/message/)
Post.find().regex('message', /message/)

 

'서버 > Node.js' 카테고리의 다른 글

TypeGraphQL ?  (0) 2020.06.05
Sequelize-cli 간단한 사용방법  (0) 2020.05.29
mongoose ?  (0) 2020.05.27
AWS s3 Image Upload  (0) 2020.05.26
Logging - Pino ?  (0) 2020.05.16
Comments