MongoDB में $unwind इनपुट दस्तावेज़ों से ऐरे फ़ील्ड को डी-कंस्ट्रक्ट करता है ताकि प्रत्येक एलिमेंट के लिए एक दस्तावेज़ आउटपुट हो। गिनती प्राप्त करने के लिए $unwind के साथ aggregate() का उपयोग करें। आइए दस्तावेज़ों के साथ एक संग्रह बनाएं:
> db.demo478.insertOne( ... { ... ... "Details" : { ... _id:1, ... "Information" : [ ... { ... "Name" : "Chris", ... "Age":21 ... }, ... { ... "Name" : "David", ... "Age":23 ... }, ... { ... ... "Name" : null, ... "Age":22 ... }, ... { ... ... "Name" : null, ... "Age":24 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8204acb0f3fa88e2279092") } > > db.demo478.insertOne( ... { ... ... "Details" : { ... _id:2, ... "Information" : [ ... { ... "Name" : "Bob", ... "Age":21 ... }, ... { ... "Name" : null, ... "Age":20 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8204adb0f3fa88e2279093") }
सभी दस्तावेज़ प्रदर्शित करें
> db.demo478.find();
आउटपुट:
{ "_id" : ObjectId("5e8204acb0f3fa88e2279092"), "Details" : { "_id" : 1, "Information" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : null, "Age" : 22 }, { "Name" : null, "Age" : 24 } ] } } { "_id" : ObjectId("5e8204adb0f3fa88e2279093"), "Details" : { "_id" : 2, "Information" : [ { "Name" : "Bob", "Age" : 21 }, { "Name" : null, "Age" : 20 } ] } }
$unwind से गिनती प्राप्त करने की क्वेरी
> db.demo478.aggregate([ ... { "$unwind": "$Details.Information" }, ... { ... "$group" : { ... "_id": "$Details.Information.Age", ... "count" : { ... "$sum": { ... "$cond": [ ... { "$gt": [ "$Details.Information.Name", null ] }, ... 1, 0 ... ] ... } ... } ... } ... }, ... { "$sort" : { "count" : -1 } } ... ])
आउटपुट
{ "_id" : 21, "count" : 2 } { "_id" : 23, "count" : 1 } { "_id" : 24, "count" : 0 } { "_id" : 20, "count" : 0 } { "_id" : 22, "count" : 0 }