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

In giá trị tài liệu trong MongoDB Shell

Để in giá trị của trường cụ thể từ tài liệu trong MongoDB Shell, có thể sử dụng phương thức forEach() kết hợp với print(). Điều này hữu ích khi cần xử lý hoặc hiển thị dữ liệu theo định dạng tùy chỉnh.

Tạo dữ liệu mẫu

> db.printDocuementValueDemo.insertOne({"InstructorName":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6804f7924bb85b3f48950") }
> db.printDocuementValueDemo.insertOne({"InstructorName":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd680577924bb85b3f48951") }
> db.printDocuementValueDemo.insertOne({"InstructorName":"David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd680637924bb85b3f48952") }

Xem tất cả tài liệu

> db.printDocuementValueDemo.find().pretty();

In giá trị trường cụ thể với forEach

Tìm tài liệu theo _id, chỉ chọn trường InstructorName, sau đó in ra:

> db.printDocuementValueDemo.find( 
  { _id : ObjectId("5cd680577924bb85b3f48951") }, 
  {InstructorName: 1, _id: 0}
).forEach(function(myDocument) { 
  print(myDocument.InstructorName); 
});

Kết quả

Sam Williams

Giải thích các thành phần

  • find(query, projection): Truy vấn với projection {InstructorName: 1, _id: 0} chỉ lấy trường cần thiết
  • forEach(function(doc) {...}): Duyệt qua từng tài liệu kết quả
  • print(): In ra console MongoDB Shell
  • myDocument.InstructorName: Truy cập trường của đối tượng tài liệu

Các cách in khác

In tất cả tên giảng viên

db.printDocuementValueDemo.find({}, {InstructorName: 1, _id: 0})
  .forEach(function(doc) { print(doc.InstructorName); });

In với định dạng tùy chỉnh

db.printDocuementValueDemo.find().forEach(function(doc) {
  print("ID: " + doc._id + ", Tên: " + doc.InstructorName);
});

Sử dụng printjson() cho đối tượng phức tạp

db.printDocuementValueDemo.find().forEach(function(doc) {
  printjson(doc);
});

Lưu ý

forEach() chỉ hoạt động trong MongoDB Shell. Khi dùng driver (Node.js, Python, v.v.), hãy sử dụng vòng lặp của ngôn ngữ lập trình đó trên cursor trả về.