Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB $or 연산자를 구현하는 방법

<시간/>

MongoDB에서 $or 연산자를 사용하여 하나 이상의 표현식을 평가합니다. 다음은 구문입니다 -

db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty();

먼저 문서로 컬렉션을 생성해 보겠습니다. −

> db.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b80a6d78f205348bc61b")
}
> db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b8266d78f205348bc61c")
}
> db.orOperatorDemo.insertOne({"StudentNames":["John"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b8346d78f205348bc61d")
}

다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -

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

이것은 다음과 같은 출력을 생성합니다 -

{
   "_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
   "StudentNames" : [
      "John",
      "Carol",
      "Sam"
   ]
}
{
   "_id" : ObjectId("5cd6b8266d78f205348bc61c"),
   "StudentNames" : [
      "Robert",
      "Chris",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd6b8346d78f205348bc61d"),
   "StudentNames" : [
      "John"
   ]
}

다음은 $or 연산자 구문에 대한 쿼리입니다. -

> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty();

이것은 다음과 같은 출력을 생성합니다 -

{
   "_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
   "StudentNames" : [
      "John",
      "Carol",
      "Sam"
   ]
}
{
   "_id" : ObjectId("5cd6b8346d78f205348bc61d"),
   "StudentNames" : [
      "John"
   ]
}