Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> MongoDB

MongoDB में दस्तावेज़ मौजूद है या नहीं जांचकर True/False कैसे लौटाएं?


count() के साथ अस्तित्व जांच

दस्तावेज़ मौजूद है या नहीं जांचने के लिए find() के साथ count() का उपयोग करें और परिणाम की तुलना 0 से करें।

उदाहरण: नमूना डेटा

> db.documentExistsOrNotDemo.insertOne({"UserId":101,"UserName":"John"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5c9932bd330fd0aa0d2fe4cf") }
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Chris"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5c9932c6330fd0aa0d2fe4d0") }
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Robert"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5c9932ce330fd0aa0d2fe4d1") }

केस 1: मौजूदा दस्तावेज़ (UserId: 101)

> db.documentExistsOrNotDemo.find({"UserId": 101}).count() > 0;

आउटपुट: true

केस 2: गैर-मौजूदा दस्तावेज़ (UserId: 110)

> db.documentExistsOrNotDemo.find({"UserId": 110}).count() > 0;

आउटपुट: false

आधुनिक विकल्प (MongoDB 4.0+):

  • db.collection.countDocuments({query}) - अधिक सटीक, सीमा के बिना।
  • db.collection.estimatedDocumentCount() - तेज़ अनुमान (क्वेरी के बिना)।

प्रदर्शन टिप: केवल अस्तित्व जांच के लिए, findOne() अधिक कुशल है क्योंकि यह पहला मिलान मिलने पर रुक जाता है:

db.documentExistsOrNotDemo.findOne({"UserId": 101}) != null
  1. - MongoDB में कैसे पता करें कि एलिमेंट दस्तावेज़ में मौजूद है?

    MongoDB दस्तावेज़ में एलिमेंट मौजूद है या नहीं जांचने के लिए MongoDB $exists का उपयोग करें। नमूना डेटा बनाना db.demo497.insertOne({details:[{}]}); सभी दस्तावेज़ देखना db.demo497.find(); { details : [ { Name : Chris }, { Name : Bob } ] } { details : [ { Name : Carol } ] } { details : [ { } ] } द

  1. - MongoDB में Nested Document में Condition Set करना

    मान लें हमें specific value से greater value वाले document find करना है। इसके लिए nested document में dot notation का उपयोग करें और $gt से condition set करें। Collection बनाना > db.demo688.insert( ... { ... information:{id:1,details:[ ... {otherDetails:{ ... values:75 ... }} ...

  1. - MongoDB में सब-डॉक्यूमेंट द्वारा सब-डॉक्यूमेंट्स फ़िल्टर करें

    इसके लिए, $unwind के साथ aggregate() का उपयोग करें। आइए दस्तावेजों के साथ एक कलेक्शन बनाते हैं: > db.demo583.insert([ { details1: [ { details2: [ { isMarried: true, Name: Chris }, { isMarried: true, Name: Bob }