MongoDB에서 $ne(not equal) 연산자는 특정 필드의 값이 지정한 값과 같지 않은 문서만 조회할 때 사용하는 비교 연산자입니다. SQL의 != 또는 <> 조건과 유사한 역할을 합니다.
$ne 연산자 기본 문법
$ne 연산자를 사용해 MongoDB를 쿼리하는 기본 문법은 다음과 같습니다.
db.yourCollectionName.find({yourFieldName:{$ne:yourValue}}).pretty();예제 컬렉션 생성하기
실습을 위해 학생 이름과 수학 점수를 담은 컬렉션을 만들어 보겠습니다. insertOne() 메서드로 문서를 하나씩 삽입합니다.
> db.notEqualToDemo.insertOne({"StudentName":"Larry","StudentMathMarks":68});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd3a6bde8cc557214c0ded")
}
> db.notEqualToDemo.insertOne({"StudentName":"Chris","StudentMathMarks":88});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd3a79de8cc557214c0dee")
}
> db.notEqualToDemo.insertOne({"StudentName":"David","StudentMathMarks":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd3a89de8cc557214c0def")
}
> db.notEqualToDemo.insertOne({"StudentName":"Carol","StudentMathMarks":69});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd3a97de8cc557214c0df0")
}저장된 전체 문서 확인하기
find() 메서드와 pretty()를 함께 사용하면 컬렉션의 모든 문서를 보기 좋게 출력할 수 있습니다.
> db.notEqualToDemo.find().pretty();
위 명령을 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5cbd3a6bde8cc557214c0ded"),
"StudentName" : "Larry",
"StudentMathMarks" : 68
}
{
"_id" : ObjectId("5cbd3a79de8cc557214c0dee"),
"StudentName" : "Chris",
"StudentMathMarks" : 88
}
{
"_id" : ObjectId("5cbd3a89de8cc557214c0def"),
"StudentName" : "David",
"StudentMathMarks" : 45
}
{
"_id" : ObjectId("5cbd3a97de8cc557214c0df0"),
"StudentName" : "Carol",
"StudentMathMarks" : 69
}$ne 연산자로 쿼리 실행하기
이제 $ne 연산자를 활용해 수학 점수가 88점이 아닌 학생만 조회해 보겠습니다.
> db.notEqualToDemo.find({StudentMathMarks:{$ne:88}}).pretty();실행 결과, Chris(88점)를 제외한 나머지 세 명의 문서만 반환됩니다.
{
"_id" : ObjectId("5cbd3a6bde8cc557214c0ded"),
"StudentName" : "Larry",
"StudentMathMarks" : 68
}
{
"_id" : ObjectId("5cbd3a89de8cc557214c0def"),
"StudentName" : "David",
"StudentMathMarks" : 45
}
{
"_id" : ObjectId("5cbd3a97de8cc557214c0df0"),
"StudentName" : "Carol",
"StudentMathMarks" : 69
}참고 사항
- $ne 연산자는 해당 필드가 존재하지 않는 문서도 함께 반환합니다. 따라서 필드가 반드시 있어야 하는 경우
$exists: true조건을 함께 사용하는 것이 좋습니다. - $ne 조건은 인덱스를 효율적으로 활용하지 못할 수 있으므로, 대량의 데이터를 다룰 때는 성능에 유의해야 합니다.