MongoDB में कलेक्शन से डॉक्यूमेंट्स डिलीट करने के लिए, आपको remove() मेथड का उपयोग करना होगा। सिंटैक्स इस प्रकार है:
db.yourCollectionName.remove(yourDeleteValue);
यहां, आइए कुछ डॉक्यूमेंट्स के साथ एक कलेक्शन बनाएं। क्वेरी इस प्रकार है:
>db.deleteDocuments.insert({"UserId":1,"UserName":"Bob","UserTechnicalSubject":"Introduction to PL/SQL"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":2,"UserName":"Carol","UserTechnicalSubject":"Introduction to MongoDB"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":3,"UserName":"John","UserTechnicalSubject":"Introduction to MySQL"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nInserted" : 1 })
आप ऊपर बनाए गए कलेक्शन से सभी डॉक्यूमेंट्स को find() कमांड की मदद से प्रदर्शित कर सकते हैं। क्वेरी इस प्रकार है:
> db.deleteDocuments.find().pretty();
निम्नलिखित आउटपुट है:
{ "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"), "UserId" : 1, "UserName" : "Bob", "UserTechnicalSubject" : "Introduction to PL/SQL" }
{ "_id" : ObjectId("5c6aaab464f3d70fcc914800"), "UserId" : 2, "UserName" : "Carol", "UserTechnicalSubject" : "Introduction to MongoDB" }
{ "_id" : ObjectId("5c6aaac764f3d70fcc914801"), "UserId" : 3, "UserName" : "John", "UserTechnicalSubject" : "Introduction to MySQL" }
{ "_id" : ObjectId("5c6aaadc64f3d70fcc914802"), "UserId" : 4, "UserName" : "Maxwell", "UserTechnicalSubject" : "Introduction to SQL Server" }
सिंगल डॉक्यूमेंट डिलीट करें
कलेक्शन से सिंगल डॉक्यूमेंट डिलीट करने के लिए, आपको remove() मेथड का उपयोग करना होगा। क्वेरी इस प्रकार है। मान लें हम "UserId:4" वाले डॉक्यूमेंट को डिलीट कर रहे हैं:
>db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nRemoved" : 1 })
अब आप find() कमांड की मदद से सभी डॉक्यूमेंट्स प्रदर्शित करके सत्यापित कर सकते हैं कि "UserId:4" डॉक्यूमेंट सफलतापूर्वक डिलीट हुआ है या नहीं। क्वेरी इस प्रकार है:
> db.deleteDocuments.find().pretty();
निम्नलिखित आउटपुट है:
{ "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"), "UserId" : 1, "UserName" : "Bob", "UserTechnicalSubject" : "Introduction to PL/SQL" }
{ "_id" : ObjectId("5c6aaab464f3d70fcc914800"), "UserId" : 2, "UserName" : "Carol", "UserTechnicalSubject" : "Introduction to MongoDB" }
{ "_id" : ObjectId("5c6aaac764f3d70fcc914801"), "UserId" : 3, "UserName" : "John", "UserTechnicalSubject" : "Introduction to MySQL" }
सभी डॉक्यूमेंट्स डिलीट करें
सभी डॉक्यूमेंट्स डिलीट करने के लिए, आपको निम्न सिंटैक्स का उपयोग करना होगा:
db.yourCollectionName.remove({ });
क्वेरी इस प्रकार है:
> db.deleteDocuments.remove({});
निम्नलिखित आउटपुट है:
WriteResult({ "nRemoved" : 3 })
हमने कलेक्शन 'deleteDocuments' से सभी डॉक्यूमेंट्स डिलीट कर दिए हैं।