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

Duyệt cursor và in document trong MongoDB?

Dùng printjson trong forEach(). Tạo collection:

> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442") }
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443") }
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444") }
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445") }

Hiển thị tất cả:

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

Duyệt cursor và in toàn bộ document:

> db.cursorDemo.find().forEach(printjson);

Chỉ in các trường cụ thể (loại _id):

> db.cursorDemo.find({}, { "StudentFullName": 1,"StudentAge":1, "_id": 0 }).forEach(printjson)

Kết quả: