เพื่อ validate schema, debug typos ใน fields หรือหา fields ที่ไม่ควรถูกตั้งค่า คุณจะต้องเข้าใจ keys ทั้งหมดใน MongoDB collection ของคุณ
หลายบริการ MongoDB-as-a-service เสนอวิธีง่ายๆ ในการทำสิ่งนี้ใน UI โดยตรง รวมถึง ObjectRocket ผู้ใช้ MongoDB มืออาชีพมักเริ่มต้นด้วย object-document mapper (ODM) เช่น Mongoose สำหรับ JS หรือ Mongoengine สำหรับ Python เพื่อสร้าง schema ที่สอดคล้องกันสำหรับแอปพลิเคชันและลด typos (ODMs ยังทำ type validation ด้วย ดังนั้นคุณจึงไม่ได้วาง string ใน field ที่มี integers และมี math ถูกนำไปใช้โดยบังเอิญ)
หากคุณไม่มี service หรือ ODM มีหลายวิธีอื่นๆ ที่คุณสามารถใช้เพื่อเข้าถึง keys นี่คือวิธีที่ดีที่สุดที่เราพบเพื่อได้ keys ทั้งหมดใน MongoDB collection สำหรับสถานการณ์ต่างๆ
ตัวอย่าง
db.activities.insert( { type : ['indoor', 'outdoor' , 'mixed'] } );
db.activities.insert( { activity : 'cycling' } );
db.activities.insert( { activity : 'skiing', location: 'Alpes', } );
db.activities.insert( { equipment : ['paddles','sunglasses'] } );
คุณต้องการได้ unique keys:
type, activity, equipment, location
MapReduce
คุณสามารถทำได้ด้วย MapReduce:
mr = db.runCommand({ "mapreduce" : "activities", "map" : function() { for (var key in this) { emit(key, null); } }, "reduce" : function(key, stuff) { return null; }, "out": "activities" + "_keys" })
เมื่อเสร็จสิ้น ให้รันคำสั่ง distinct บน collection ที่ได้ เพื่อหา keys ทั้งหมด:
db.activities_keys.distinct("_id")
หากคุณต้องการรายการ unique keys ทั้งหมดใน subdocument ให้แก้ไขบรรทัดนี้:
for (var key in this.first_level.second_level.nth_level) { emit(key, null); }
Aggregation
คุณยังสามารถใช้ aggregation ได้ วิธีนี้ใช้งานได้กับ drivers ทั้งหมดที่รองรับ aggregate framework ด้วย aggregations ของคุณ $sample หรือ $limit สามารถใช้เพื่อลด overhead
Note: การรันด้วย primary read preference อาจส่งผลต่อ performance พิจารณารันด้วย secondary read preference
ใช้ aggregation พร้อม $objectToArray (พร้อมใช้งานใน version 3.4.4 ขึ้นไป) เพื่อแปลง key และ value pairs ทั้งหมดระดับบนสุดเป็น document arrays ตามด้วย $unwind และ $group พร้อม $addToSet เพื่อได้ distinct keys ทั่วทั้ง collection
$$ROOT สำหรับอ้างอิง top level document
db.activities.aggregate([ {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}}, {"$unwind":"$arrayofkeyvalue"}, {"$group":{"_id":null,"allkeys":{"$addToSet":"$arrayofkeyvalue.k"}}} ])
Get keys ใน single document
คุณยังสามารถใช้ aggregation เพื่อได้ keys ใน single document:
db.activities.aggregate([ {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}}, {"$project":{"keys":"$arrayofkeyvalue.k"}} ])
Mongo shell
คุณยังสามารถลองทำภายใต้ mongo shell client:
var allKeys = {}; db.YOURCOLLECTION.find().forEach(function(doc){Object.keys(doc).forEach(function(key){allKeys[key]=1})}); allKeys;
Output fields สำหรับ single document
หากคุณต้องการ output ของ fields สำหรับ single document ใน collection (เพราะอาจมี keys ต่างกันหมด) ใช้คำสั่งต่อไปนี้:
doc=db.thinks.findOne(); for (key in doc) print(key);
Python
หรือ คุณสามารถใช้ Python ได้ นี่คืนค่า set ของ top-level keys ทั้งหมดใน collection:
#Using pymongo and connection named 'db' reduce( lambda all_keys, rec_keys: all_keys | set(rec_keys), map(lambda d: d.keys(), db.things.find()), set() )
JavaScript
หรือ คุณสามารถใช้ JavaScript ได้:
db.collection('collectionName').mapReduce(
function() { for (var key in this) { emit(key, null); } },
function(key, stuff) { return null; },
{ "out": "allFieldNames" },
function(err, results) {
var fields = db.collection('allFieldNames').distinct('_id');
fields .then(function(data) {
var finalData = { "status": "success", "fields": data };
res.send(finalData);
delteCollection(db, 'allFieldNames');
})
.catch(function(err) {
res.send(err);
delteCollection(db, 'allFieldNames');
});
});
หลังจากอ่าน collection ใหม่ที่สร้างขึ้น "allFieldNames" ให้ลบมัน
db.collection("allFieldNames").remove({}, function (err,result) { db.close(); return; });
ตัวเลือกเยอะมาก...
คุณมีตัวเลือกมากมายในการได้ Mongo keys เหล่านี้! หากคุณ overwhelmed ด้วย MongoDB management และต้องการ focus บน code แทน database management เราอยู่ที่นี่สำหรับคุณ ลอง database platform และ white glove support ของเราฟรี