MongoDB 中如何用 WHERE IN(1,2,…)


MongoDB 中類似於 WHERE IN(1,2,....) 的語句是 $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
}

以下查詢代表 MongoDB 中用 $in 運算子表示的 where in

> 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
}

更新時間:2019 年 7 月 30 日

188 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.