MongoDB में एक ही दस्तावेज़ के एकाधिक फील्ड या सरणी तत्वों की तुलना करने के लिए $where ऑपरेटर का उपयोग करें जो JavaScript एक्सप्रेशन का मूल्यांकन करता है।
उदाहरण
सरणी वाला दस्तावेज़ बनाएं:
> db.comparingMultiplePropertiesDemo.insertOne({"Values":[10,70,60]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf228fcb64a577be5a2bc0a") }
दस्तावेज़ देखें:
> db.comparingMultiplePropertiesDemo.find().pretty();
{ "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"), "Values" : [ 10, 70, 60 ] }
केस 1: दूसरी तत्व तीसरे से बड़ा है (सही)
> db.comparingMultiplePropertiesDemo.find({ $where: "this.Values[1] > this.Values[2]" });
{ "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"), "Values" : [ 10, 70, 60 ] }
70 > 60 सही है, इसलिए दस्तावेज़ लौटाया गया।
केस 2: दूसरी तत्व तीसरे से छोटा है (गलत)
> db.comparingMultiplePropertiesDemo.find({ $where: "this.Values[1] < this.Values[2]" });
कोई परिणाम नहीं - 70 < 60 गलत है।
महत्वपूर्ण नोट्स:
thisवर्तमान दस्तावेज़ को संदर्भित करता है- सरणी इंडेक्स 0-आधारित हैं:
Values[0],Values[1],Values[2] $whereJavaScript इंजन का उपयोग करता है - धीमा होता है, बड़े डेटासेट के लिए अनुशंसित नहीं
बेहतर विकल्प: एग्रीगेशन पाइपलाइन
db.collection.aggregate([
{$addFields: {comparison: {$gt: [{$arrayElemAt: ["$Values", 1]}, {$arrayElemAt: ["$Values", 2]}]}}},
{$match: {comparison: true}},
{$project: {comparison: 0}}
])
यह तरीका इंडेक्स का उपयोग कर सकता है और अधिक प्रदर्शनकारी है।