distinct() और JavaScript map() का उपयोग करके पहला शब्द निकालें
MongoDB में किसी स्ट्रिंग फ़ील्ड के विशिष्ट मानों से पहला शब्द निकालने के लिए distinct() मेथड के साथ JavaScript map() फ़ंक्शन का उपयोग करें।
उदाहरण: संग्रह बनाना
> db.distinctFirstWordDemo.insertOne({
"_id": 100,
"StudentName": "John",
"StudentFeature": "John is a good player",
"Subject": "MongoDB"
});
{ "acknowledged": true, "insertedId": 100 }
> db.distinctFirstWordDemo.insertOne({
"_id": 101,
"StudentName": "Carol",
"StudentFeature": "Carol is not a good player",
"Subject": "MongoDB"
});
{ "acknowledged": true, "insertedId": 101 }
सभी डॉक्यूमेंट्स देखना
> db.distinctFirstWordDemo.find().pretty();
{
"_id": 100,
"StudentName": "John",
"StudentFeature": "John is a good player",
"Subject": "MongoDB"
}
{
"_id": 101,
"StudentName": "Carol",
"StudentFeature": "Carol is not a good player",
"Subject": "MongoDB"
}
पहला शब्द विशिष्ट प्राप्त करने की क्वेरी
distinct() से StudentFeature के विशिष्ट मान लें, फिर प्रत्येक स्ट्रिंग को स्प्लिट करके पहला शब्द लें:
> student = db.distinctFirstWordDemo.distinct("StudentFeature", {"Subject": "MongoDB"}).map(function(st) {
return st.split(" ")[0];
});
[ "John", "Carol" ]
> printjson(student);
आउटपुट:
[ "John", "Carol" ]
यह तरीका क्लाइंट-साइड JavaScript प्रोसेसिंग का उपयोग करता है। सर्वर-साइड एग्रीगेशन के लिए $split (MongoDB 4.4+) का उपयोग करें।