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
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP