Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách lấy tên tất cả các trường trong collection MongoDB

Bạn có thể sử dụng khái niệm Map Reduce để lấy tên tất cả các trường. Trước hết, hãy tạo một collection với document:

> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90") }

Truy vấn hiển thị tất cả document:

> db.getAllFieldNamesDemo.find();

Kết quả:

{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }

Truy vấn Map Reduce để lấy tên tất cả các trường:

> 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");

Kết quả hiển thị tên các trường:

[ "StudentAge", "StudentFirstName", "_id" ]