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

Lấy giá trị distinct (duy nhất) của trường FirstName trong MongoDB

Phương thức distinct() trả về mảng các giá trị duy nhất (không trùng lặp) của một trường xác định trên tất cả tài liệu trong collection (hoặc thỏa mãn bộ lọc).

Dữ liệu mẫu

> db.demo303.insertOne({FirstName:"Chris",LastName:"Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea0f6f8647eb59e56202f") }
> db.demo303.insertOne({FirstName:"John",LastName:"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea104f8647eb59e562030") }
> db.demo303.insertOne({FirstName:"Chris",LastName:"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea10df8647eb59e562031") }
> db.demo303.insertOne({FirstName:"John",LastName:"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea121f8647eb59e562032") }
> db.demo303.insertOne({FirstName:"David",LastName:"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea136f8647eb59e562033") }

Xem dữ liệu

> db.demo303.find().pretty();
{ "_id" : ObjectId("5e4ea0f6f8647eb59e56202f"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5e4ea104f8647eb59e562030"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5e4ea10df8647eb59e562031"), "FirstName" : "Chris", "LastName" : "Smith" }
{ "_id" : ObjectId("5e4ea121f8647eb59e562032"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5e4ea136f8647eb59e562033"), "FirstName" : "David", "LastName" : "Miller" }

Lấy distinct FirstName

> db.demo303.distinct("FirstName");

Kết quả

[ "Chris", "John", "David" ]

Ứng dụng: distinct() thường dùng để lấy danh sách giá trị cho dropdown, filter UI, hoặc thống kê nhanh. Có thể thêm bộ lọc: db.collection.distinct("field", { status: "active" }). Kết quả trả về mảng, thứ tự không đảm bảo.