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

Lấy tất cả _id của tài liệu trong MongoDB Collection

Để lấy danh sách chỉ chứa _id của tất cả tài liệu, dùng find() với projection loại trừ các trường khác ({"field": 0}) hoặc chỉ include _id. Kết quả trả về cursor chứa các tài liệu chỉ có _id.

Dữ liệu mẫu

> db.demo169.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e36975e9e4f06af551997d7") }
> db.demo169.insertOne({"StudentName":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3697629e4f06af551997d8") }
> db.demo169.insertOne({"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3697679e4f06af551997d9") }

Xem dữ liệu

> db.demo169.find();
{ "_id" : ObjectId("5e36975e9e4f06af551997d7"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e3697629e4f06af551997d8"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e3697679e4f06af551997d9"), "StudentName" : "David" }

Truy vấn chỉ lấy _id (exclude StudentName)

> var iterator = db.demo169.find({}, {"StudentName": 0});

Duyệt cursor in _id

> iterator;
{ "_id" : ObjectId("5e36975e9e4f06af551997d7") }
{ "_id" : ObjectId("5e3697629e4f06af551997d8") }
{ "_id" : ObjectId("5e3697679e4f06af551997d9") }

Cách hiệu quả hơn: Dùng db.demo169.find({}, {_id: 1}) (include chỉ _id) hoặc db.demo169.distinct("_id") (trả về mảng _id duy nhất, nhanh hơn cho collection lớn). Trong driver, dùng projection {_id: 1} và chỉ đọc _id từ cursor.