MongoDB कलेक्शन में मौजूद सभी फ़ील्ड नाम प्राप्त करने के लिए Map-Reduce ऑपरेशन का उपयोग कर सकते हैं। यह तरीका तब उपयोगी होता है जब आपको डायनामिक रूप से फ़ील्ड नामों की सूची चाहिए।
उदाहरण
पहले एक कलेक्शन बनाएं और दस्तावेज़ डालें:
> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90") }
दस्तावेज़ देखने के लिए:
> db.getAllFieldNamesDemo.find();
आउटपुट:
{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }
Map-Reduce से फ़ील्ड नाम प्राप्त करें
> myMapReduce = db.runCommand({
"mapreduce" : "getAllFieldNamesDemo",
"map" : function() {
for (var myKey in this) { emit(myKey, null); }
},
"reduce" : function(myKey, s) { return null; },
"out": "getAllFieldNamesDemo" + "_k"
})
{
"result" : "getAllFieldNamesDemo_k",
"timeMillis" : 1375,
"counts" : {
"input" : 1,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1
}
> db[myMapReduce.result].distinct("_id");
आउटपुट:
[ "StudentAge", "StudentFirstName", "_id" ]
नोट: MongoDB 4.4+ में आप $objectToArray और $unionWith एग्रीगेशन स्टेज का उपयोग करके भी यही परिणाम प्राप्त कर सकते हैं, जो अधिक कुशल है।