WHERE IN(1,2、…)と同等のMongoDB?
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
} -
配列に特定の属性を含むMongoDBドキュメントを取得します
このために、ドット(。)表記と一緒に$andを使用できます。まず、ドキュメントを使用してコレクションを作成しましょう- >db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]}); { "acknowledged" :
-
配列の要素が特定の値を持つMongoDBドキュメントを見つけますか?
MongoDBのドキュメントを照合するには、$elemMatchを使用します。まず、ドキュメントを使用してコレクションを作成しましょう- > db.demo15.insertOne({"Details":[{"Score":56},{"Score":78}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f7806d7df943a7cec4fab") }