Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 필드가 존재할 때만 조건을 적용하는 방법 ($or·$exists 연산자 활용)

MongoDB에서 특정 필드가 실제로 존재하는 경우에만 조건을 적용하고 싶다면 $or 연산자를 활용하면 됩니다. $or 연산자는 배열로 전달된 여러 조건 중 하나라도 참이면 해당 문서를 반환하기 때문에, "필드 자체가 없는 문서"와 "필드가 존재하면서 조건을 충족하는 문서"를 한 번의 쿼리로 함께 조회할 수 있습니다.

1. 샘플 컬렉션 생성하기

먼저 insertOne() 메서드를 사용해 테스트용 컬렉션에 문서를 삽입합니다. 마지막 문서(Robert)에는 StudentAge 필드가 의도적으로 빠져 있다는 점에 유의하세요.

> db.applyConditionDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80b78623186894665ae36")
}
> db.applyConditionDemo.insertOne({"StudentName":"Sam","StudentAge":23,"StudentMarks":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80b87623186894665ae37")
}
> db.applyConditionDemo.insertOne({"StudentName":"David","StudentAge":21,"StudentMarks":65});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80b95623186894665ae38")
}
> db.applyConditionDemo.insertOne({"StudentName":"Carol","StudentAge":24,"StudentMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80ba3623186894665ae39")
}
> db.applyConditionDemo.insertOne({"StudentName":"Chris","StudentAge":21,"StudentMarks":88});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80bae623186894665ae3a")
}
> db.applyConditionDemo.insertOne({"StudentName":"Robert","StudentMarks":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb80c3d623186894665ae3b")
}

2. 저장된 전체 문서 확인하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.

> db.applyConditionDemo.find().pretty();

위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.

{
   "_id" : ObjectId("5cb80b78623186894665ae36"),
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentMarks" : 45
}
{
   "_id" : ObjectId("5cb80b87623186894665ae37"),
   "StudentName" : "Sam",
   "StudentAge" : 23,
   "StudentMarks" : 55
}
{
   "_id" : ObjectId("5cb80b95623186894665ae38"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "StudentMarks" : 65
}
{
   "_id" : ObjectId("5cb80ba3623186894665ae39"),
   "StudentName" : "Carol",
   "StudentAge" : 24,
   "StudentMarks" : 78
}
{
   "_id" : ObjectId("5cb80bae623186894665ae3a"),
   "StudentName" : "Chris",
   "StudentAge" : 21,
   "StudentMarks" : 88
}
{
   "_id" : ObjectId("5cb80c3d623186894665ae3b"),
   "StudentName" : "Robert",
   "StudentMarks" : 98
}

3. 필드가 존재하는 경우에만 조건 적용하기

이제 핵심 부분입니다. $or 연산자와 $exists 연산자를 조합하면 원하는 동작을 간단히 구현할 수 있습니다.

> db.applyConditionDemo.find({ $or: [ { StudentAge: { $exists:false } }, { StudentAge:21 } ]}).pretty();

이 쿼리의 동작 방식을 살펴보면 다음과 같습니다.

  • { StudentAge: { $exists:false } } — StudentAge 필드가 아예 없는 문서를 매칭합니다. (Robert)
  • { StudentAge: 21 } — StudentAge 필드가 존재하면서 값이 21인 문서를 매칭합니다. (Larry, David, Chris)

두 조건이 $or로 연결되어 있으므로 둘 중 하나만 만족해도 결과에 포함됩니다. 반면 Sam(23)과 Carol(24)처럼 필드는 존재하지만 값이 21이 아닌 문서는 결과에서 제외됩니다.

실행 결과는 다음과 같습니다.

{
   "_id" : ObjectId("5cb80b78623186894665ae36"),
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentMarks" : 45
}
{
   "_id" : ObjectId("5cb80b95623186894665ae38"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "StudentMarks" : 65
}
{
   "_id" : ObjectId("5cb80bae623186894665ae3a"),
   "StudentName" : "Chris",
   "StudentAge" : 21,
   "StudentMarks" : 88
}
{
   "_id" : ObjectId("5cb80c3d623186894665ae3b"),
   "StudentName" : "Robert",
   "StudentMarks" : 98
}

마무리

이처럼 $or 연산자 안에 "$exists: false" 조건과 실제 필터 조건을 함께 넣어주면, 필드가 없는 문서는 그대로 통과시키고 필드가 있는 문서에만 조건을 적용할 수 있습니다. 스키마가 유연한 MongoDB 환경에서 선택적(optional) 필드를 다룰 때 매우 유용하게 활용되는 패턴이니 꼭 기억해 두세요.