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

MongoDB에서 청구 주소와 배송 주소가 동일한 문서 조회하기 – $where 연산자 활용법

MongoDB에서 두 필드의 값이 서로 같은지 비교하고 해당 조건을 만족하는 문서를 조회하려면 $where 연산자를 사용할 수 있습니다. 이 글에서는 청구 주소(billingAddress)가 배송 주소(deliveryAddress)와 일치하는 문서를 찾는 방법을 단계별로 살펴보겠습니다.

1. 테스트용 컬렉션 생성 및 데이터 삽입

먼저 예제에 사용할 컬렉션을 만들고 문서를 삽입합니다.

> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e92c117fd2d90c177b5bccc")
}
> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e92c11bfd2d90c177b5bccd")
}
> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e92c11ffd2d90c177b5bcce")
}
> db.demo589.insertOne({deliveryAddress:"UK",billingAddress:"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e92c127fd2d90c177b5bccf")
}

총 4개의 문서가 삽입되었으며, 각 문서는 서로 다른 주소 조합을 가지고 있습니다.

2. find() 메서드로 전체 문서 확인하기

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

> db.demo589.find();

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

{ "_id" : ObjectId("5e92c117fd2d90c177b5bccc"), "deliveryAddress" : "US", "billingAddress" : "UK" }
{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }
{ "_id" : ObjectId("5e92c11ffd2d90c177b5bcce"), "deliveryAddress" : "US", "billingAddress" : "AUS" }
{ "_id" : ObjectId("5e92c127fd2d90c177b5bccf"), "deliveryAddress" : "UK", "billingAddress" : "US" }

3. $where를 사용해 청구 주소와 배송 주소가 같은 문서 조회하기

두 필드의 값을 비교하려면 일반적인 쿼리 문법으로는 불가능하며, JavaScript 표현식을 평가하는 $where 절이 필요합니다. 아래 쿼리는 deliveryAddress와 billingAddress 값이 동일한 문서만 반환합니다.

> db.demo589.find( { $where: "this.deliveryAddress == this.billingAddress" } );

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

{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }

정리 및 참고 사항

$where 연산자는 this.deliveryAddress == this.billingAddress처럼 같은 문서 내의 두 필드 값을 직접 비교할 때 유용합니다. 다만 주의할 점도 있습니다.

  • 성능: $where는 각 문서마다 JavaScript를 실행하므로 인덱스를 활용하지 못하고 성능이 느릴 수 있습니다. 가능하면 $expr과 aggregation 연산자($eq 등)를 사용하는 것이 권장됩니다.
  • $expr 대안: MongoDB 3.6 이상에서는 { $expr: { $eq: ["$deliveryAddress", "$billingAddress"] } } 형태로 동일한 결과를 더 효율적으로 얻을 수 있습니다.
  • 보안: 사용자 입력값을 그대로 $where 문자열에 포함시키지 않도록 주의해야 합니다.