MongoDB में $in ऑपरेटर का उपयोग
SQL के WHERE IN (1,2,...) क्लॉज का MongoDB में समतुल्य $in ऑपरेटर है। यह ऑपरेटर किसी फील्ड के मान को निर्दिष्ट मानों की सरणी में से किसी एक से मिलान करने की अनुमति देता है।
सिंटैक्स
db.yourCollectionName.find({yourFieldName:{$in:[yourValue1,yourValue2,....N]}}).pretty();
उदाहरण: संग्रह बनाना और दस्तावेज़ डालना
सबसे पहले, एक संग्रह whereInDemo बनाते हैं और कुछ नमूना दस्तावेज़ डालते हैं:
> 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") }
सभी दस्तावेज़ प्रदर्शित करना
> 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 ऑपरेटर के साथ क्वेरी
उन छात्रों को ढूंढें जिनका गणित स्कोर 97, 98, या 99 है:
> 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 }
नोट: $in ऑपरेटर सरणी में किसी भी मान से मिलान करता है, जिससे यह SQL के IN क्लॉज के लिए एक सीधा विकल्प बन जाता है।