WHERE IN(1,2,....)에 해당하는 MongoDB는 $in 연산자입니다. 구문은 다음과 같습니다.
db.yourCollectionName.find({yourFieldName:{$in:[yourValue1,yourValue2,....N]}}).pretty(); 먼저 문서로 컬렉션을 생성하겠습니다.
> db.whereInDemo.insertOne({"StudentName":"John","StudentMathScore":57});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281ec6304881c5ce84ba5")
}
> db.whereInDemo.insertOne({"StudentName":"Larry","StudentMathScore":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281f56304881c5ce84ba6")
}
> db.whereInDemo.insertOne({"StudentName":"Chris","StudentMathScore":98});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281fd6304881c5ce84ba7")
}
> db.whereInDemo.insertOne({"StudentName":"Robert","StudentMathScore":99});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2820a6304881c5ce84ba8")
}
> db.whereInDemo.insertOne({"StudentName":"Bob","StudentMathScore":97});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca282206304881c5ce84ba9")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다.
> db.whereInDemo.find().pretty();
그러면 다음과 같은 출력이 생성됩니다.
{
"_id" : ObjectId("5ca281ec6304881c5ce84ba5"),
"StudentName" : "John",
"StudentMathScore" : 57
}
{
"_id" : ObjectId("5ca281f56304881c5ce84ba6"),
"StudentName" : "Larry",
"StudentMathScore" : 89
}
{
"_id" : ObjectId("5ca281fd6304881c5ce84ba7"),
"StudentName" : "Chris",
"StudentMathScore" : 98
}
{
"_id" : ObjectId("5ca2820a6304881c5ce84ba8"),
"StudentName" : "Robert",
"StudentMathScore" : 99
}
{
"_id" : ObjectId("5ca282206304881c5ce84ba9"),
"StudentName" : "Bob",
"StudentMathScore" : 97
} 다음은 $in 연산자를 사용하여 MongoDB에서 where와 동일한 것을 나타내는 쿼리입니다.
> db.whereInDemo.find({StudentMathScore:{$in:[97,98,99]}}).pretty(); 그러면 다음과 같은 출력이 생성됩니다.
{
"_id" : ObjectId("5ca281fd6304881c5ce84ba7"),
"StudentName" : "Chris",
"StudentMathScore" : 98
}
{
"_id" : ObjectId("5ca2820a6304881c5ce84ba8"),
"StudentName" : "Robert",
"StudentMathScore" : 99
}
{
"_id" : ObjectId("5ca282206304881c5ce84ba9"),
"StudentName" : "Bob",
"StudentMathScore" : 97
}