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

MongoDB에서 두 필드를 비교하는 쿼리 조건 작성 방법

MongoDB에서 두 개의 필드 값을 서로 비교하여 조건에 맞는 문서를 조회하려면 $where 연산자와 JavaScript 함수를 함께 사용해야 합니다. 일반적인 비교 연산자($gt, $lt 등)는 특정 필드와 고정된 값만 비교할 수 있지만, 서로 다른 두 필드 간의 비교는 $where 절 안에서 자바스크립트 표현식으로 처리해야 합니다.

기본 문법

두 필드를 비교하는 쿼리 조건은 아래와 같은 형태로 작성합니다.

db.yourCollectionName.find( { $where: function() { return this.yourFirstFieldName < this.yourSecondFieldName } } ).pretty();

예제 컬렉션 생성하기

문법을 이해하기 위해 학생 정보가 담긴 컬렉션을 만들어 보겠습니다. 아래 쿼리로 컬렉션에 문서를 삽입합니다.

> db.comparingTwoFieldsDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":99,"StudentPhysicsMarks":98});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c8ac09e6cea1f28b7aa0807")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentMathMarks":79,"StudentPhysicsMarks":89});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c8ac0b46cea1f28b7aa0808")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"David","StudentAge":24,"StudentMathMarks":39,"StudentPhysicsMarks":45});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c8ac0c96cea1f28b7aa0809")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":87,"StudentPhysicsMarks":78});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c8ac0e06cea1f28b7aa080a")
}

저장된 전체 문서 확인하기

find() 메서드를 사용하면 컬렉션의 모든 문서를 화면에 출력할 수 있습니다.

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

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

{
    "_id" : ObjectId("5c8ac09e6cea1f28b7aa0807"),
    "StudentName" : "John",
    "StudentAge" : 21,
    "StudentMathMarks" : 99,
    "StudentPhysicsMarks" : 98
}
{
    "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
    "StudentName" : "Carol",
    "StudentAge" : 22,
    "StudentMathMarks" : 79,
    "StudentPhysicsMarks" : 89
}
{
    "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
    "StudentName" : "David",
    "StudentAge" : 24,
    "StudentMathMarks" : 39,
    "StudentPhysicsMarks" : 45
}
{
    "_id" : ObjectId("5c8ac0e06cea1f28b7aa080a"),
    "StudentName" : "Bob",
    "StudentAge" : 23,
    "StudentMathMarks" : 87,
    "StudentPhysicsMarks" : 78
}

두 필드를 비교하는 쿼리 실행하기

이제 수학 점수(StudentMathMarks)가 물리 점수(StudentPhysicsMarks)보다 낮은 학생만 조회하는 쿼리를 실행해 보겠습니다.

> db.comparingTwoFieldsDemo.find( { $where: function() { return this.StudentMathMarks < this.StudentPhysicsMarks } } ).pretty();

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

{
    "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
    "StudentName" : "Carol",
    "StudentAge" : 22,
    "StudentMathMarks" : 79,
    "StudentPhysicsMarks" : 89
}
{
    "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
    "StudentName" : "David",
    "StudentAge" : 24,
    "StudentMathMarks" : 39,
    "StudentPhysicsMarks" : 45
}

결과 분석 및 참고 사항

위 결과에서 Carol(수학 79점, 물리 89점)과 David(수학 39점, 물리 45점)만 반환된 것을 확인할 수 있습니다. John은 수학 점수가 더 높고, Bob 역시 수학 점수(87점)가 물리 점수(78점)보다 높기 때문에 조건에서 제외되었습니다.

$where 연산자는 유연하지만 각 문서마다 자바스크립트를 실행해야 하므로 성능이 떨어질 수 있다는 점에 유의하세요. 대량의 데이터를 다룰 때는 가능한 한 집계 파이프라인의 $expr 연산자나 인덱스를 활용하는 것이 더 효율적입니다.