뭐든 즐기면서 ;)

MongoDB 조회 본문

DB(데이타베이스)/MongoDB

MongoDB 조회

Tada.*+ 2023. 5. 13. 19:23
728x90
  • $gt / $gte / $lt / $lte 
  • $or
  • $in <> $nin
  • $not (= 정규 표현식과 함께 사용 가능)
> db.collection.find({ age: {$gte: 18, $lte: 30} }); // 18~30세
> db.collection.find({ age: {$in : [18,30]} }); // age가 18과 30에 해당하는 document 조회
> db.collection.find({ $or: [{fileName1: value1}, {fileName2: value2}] })

// $or과 $in을 함께 사용
> db.collection.find({ $or: [{fileName1: {$in: [조건1,조건2]}}, {fileName2: value2}] })
  • null 조회
> db.collection.find();
{_id: 111, y: null}
{_id: 222, bb: '1111'}
{_id: 333, bb: '2222'}

// 아래와 같이 조회할 경우 'y' field를 갖고 있지 않은 document까지 모두 조회된다.
> db.collection.find({'y': null});
{_id: 111, y: null}
{_id: 222, bb: '1111'}
{_id: 333, bb: '2222'}

// y가 null인 document만 뽑으려면 $exists를 이용해야 한다.
> db.collection.find({y: {$eq: null, $exists: true}});
{_id: 111, y: null}
  • 배열관련
    • $all
      // apple과 banana 모두를 포함한 fruit 배열이 있는 document를 반환
      > db.collection.find({fruits: {$all: ["apple", "banana"]}})
    • 배열 index 지정
      // fruits 배열의 index 2의 값이 banana인 document를 반환
      > db.collection.find({fruits.2 : "banana"})
    • $size
      // 배열의 길이가 2인 document 반환
      > db.collection.find({fruits: {$size : 2}})
    • $slice
      > db.collection.find({comments: {$slice: 10}}) // 댓글 배열 앞에 10개를 반환
      > db.collection.find({comments: {$slice: -10}}) // 댓글 배열 뒤에(나중에 달린 댓글) 10개를 반환

내장 도큐먼트 조회

{
	name: {
    	first: "Joe"
        ,last: "Schmoe"
    }
    ,age: 45
}

위와 같은 다큐먼트가 있을 때 조회 방법

  1. db.collection.find({ name: {first: "Joe", last: "Schmoe"} }) >> 형식과 field 위치가 다큐먼트 그대로여야 한다.
    db.collection.find({ name: {last: "Schmoe", first: "Joe"} }) >> 에러 발생
  2. db.collection.find({ name.first: "Joe", name.last: "Schmoe" }) << 권장하는 방법(점 표기법 dot notation)
728x90

'DB(데이타베이스) > MongoDB' 카테고리의 다른 글

MongoDB field 정렬 시 비교 순서  (0) 2023.06.01
MongoDB $elemMatch  (3) 2023.05.30
MongoDB createCollection validator  (0) 2023.05.11
MongoDB findOneAndUpdate vs updateOne  (0) 2023.05.09
MongoDB arrayFilters  (0) 2023.05.04
Comments