Để trả về document mà không bao gồm trường _id (ObjectId), hãy đặt _id: 0 trong projection. Trước tiên, tạo một collection với các document:
> db.returnDocumentWithoutObjectId.insertOne({"Name":"Carol","Age":25});
{ "acknowledged": true, "insertedId": ObjectId("5ce8ba6c78f00858fb12e8fa") }
> db.returnDocumentWithoutObjectId.insertOne({"Name":"Sam","Age":21});
{ "acknowledged": true, "insertedId": ObjectId("5ce8ba6d78f00858fb12e8fb") }
> db.returnDocumentWithoutObjectId.insertOne({"Name":"John","Age":23});
{ "acknowledged": true, "insertedId": ObjectId("5ce8ba6f78f00858fb12e8fc") }
Truy vấn hiển thị tất cả document bằng find():
> db.returnDocumentWithoutObjectId.find();
Kết quả mặc định (có _id):
{ "_id": ObjectId("5ce8ba6c78f00858fb12e8fa"), "Name": "Carol", "Age": 25 }
{ "_id": ObjectId("5ce8ba6d78f00858fb12e8fb"), "Name": "Sam", "Age": 21 }
{ "_id": ObjectId("5ce8ba6f78f00858fb12e8fc"), "Name": "John", "Age": 23 }
Truy vấn trả về document không có ObjectId:
> db.returnDocumentWithoutObjectId.find({}, {_id: 0});
Kết quả:
{ "Name": "Carol", "Age": 25 }
{ "Name": "Sam", "Age": 21 }
{ "Name": "John", "Age": 23 }