MongoDB में ऐरे क्वेरी: $where और डायरेक्ट मैच
इंटीजर ऐरे वाले डॉक्यूमेंट खोजने के लिए $where ऑपरेटर या डायरेक्ट ऐरे वैल्यू मैच का उपयोग करें।
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{ "acknowledged": true, "insertedId": ObjectId("5cd2a219345990cee87fd88c") }
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{ "acknowledged": true, "insertedId": ObjectId("5cd2a22a345990cee87fd88d") }
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{ "acknowledged": true, "insertedId": ObjectId("5cd2a23c345990cee87fd88e") }
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{ "acknowledged": true, "insertedId": ObjectId("5cd2a24d345990cee87fd88f") }
सभी डॉक्यूमेंट देखें
> db.searchDocumentArrayIntegerDemo.find().pretty();
{
"_id": ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName": "John",
"StudentScores": [45, 78, 89, 90]
}
{
"_id": ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName": "Larry",
"StudentScores": [45, 43, 34, 33]
}
{
"_id": ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName": "Chris",
"StudentScores": []
}
{
"_id": ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName": "David",
"StudentScores": [99]
}
केस 1: कम से कम एक एलिमेंट वाले ऐरे खोजें
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" });
{
"_id": ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName": "John",
"StudentScores": [45, 78, 89, 90]
}
{
"_id": ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName": "Larry",
"StudentScores": [45, 43, 34, 33]
}
{
"_id": ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName": "David",
"StudentScores": [99]
}
केस 2: ऐरे में कॉमन वैल्यू वाले डॉक्यूमेंट खोजें
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});
{
"_id": ObjectId("5cd2a219345990cee87fd88c"),
"StudentScores": [45, 78, 89, 90]
}
{
"_id": ObjectId("5cd2a22a345990cee87fd88d"),
"StudentScores": [45, 43, 34, 33]
}
बेहतर विकल्प
$where जावास्क्रिप्ट इवैल्यूएशन का उपयोग करता है जो धीमा हो सकता है। बेहतर परफॉरमेंस के लिए:
- ऐरे लेंथ चेक:
{ StudentScores: { $exists: true, $ne: [] } } - ऐरे में वैल्यू खोजें:
{ StudentScores: 45 }(MongoDB ऑटोमैटिकली ऐरे में खोजता है)