MongoDB में $or ऑपरेटर से ऐरे एलिमेंट मैच करके पहला डॉक्यूमेंट प्राप्त करें
ऐरे के अंदर ऑब्जेक्ट के किसी भी फ़ील्ड से मैच करने के लिए $or उपयोग करें और limit(1) से केवल पहला परिणाम लें।
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.matchElementInArrayDemo.insertOne({
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "US", "StudentSkills": "MongoDB"},
{"StudentCountryName": "UK", "StudentSkills": "Java"}
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd423282cba06f46efe9ee2") }
> db.matchElementInArrayDemo.insertOne({
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "AUS", "StudentSkills": "PHP"},
{"StudentCountryName": "US", "StudentSkills": "MongoDB"}
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd423412cba06f46efe9ee3") }
सभी डॉक्यूमेंट देखें
> db.matchElementInArrayDemo.find().pretty();
{
"_id": ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "US", "StudentSkills": "MongoDB"},
{"StudentCountryName": "UK", "StudentSkills": "Java"}
]
}
{
"_id": ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "AUS", "StudentSkills": "PHP"},
{"StudentCountryName": "US", "StudentSkills": "MongoDB"}
]
}
$or से US देश या MongoDB स्किल वाले ऐरे एलिमेंट मैच करें
> db.matchElementInArrayDemo.find({
$or: [
{"StudentOtherDetails.StudentCountryName": "US"},
{"StudentOtherDetails.StudentSkills": "MongoDB"}
]
}).limit(1);
{ "_id": ObjectId("5cd423282cba06f46efe9ee2"), "StudentName": "Chris", "StudentOtherDetails": [{"StudentCountryName": "US", "StudentSkills": "MongoDB"}, {"StudentCountryName": "UK", "StudentSkills": "Java"}] }
व्याख्या
StudentOtherDetails.StudentCountryName- ऐरे के हर ऑब्जेक्ट में चेक करता है$or- दोनों कंडीशन में से कोई भी सच हो तो डॉक्यूमेंट मैचlimit(1)- केवल पहला मैचिंग डॉक्यूमेंट लौटाता है- दोनों डॉक्यूमेंट मैच करते हैं (दोनों में US और MongoDB हैं), पहला लौटा
नोट: $elemMatch से अंतर
$or में प्रत्येक कंडीशन अलग-अलग ऐरे एलिमेंट पर लागू हो सकती है। अगर एक ही ऐरे एलिमेंट पर दोनों कंडीशन चाहिए तो $elemMatch उपयोग करें:
db.matchElementInArrayDemo.find({
StudentOtherDetails: {
$elemMatch: {
$or: [
{StudentCountryName: "US"},
{StudentSkills: "MongoDB"}
]
}
}
})