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

Lấy giá trị distinct của trường mảng qua các index trong MongoDB

Để lấy các giá trị distinct (duy nhất) của một trường mảng trên các index, dùng phương thức distinct().

Ví dụ: Tạo collection distinctAggregation:

> db.distinctAggregation.insertOne({"UserName":"Larry","UserPost":["Hi","Hello"]});
> db.distinctAggregation.insertOne({"UserName":"Chris","UserPost":["Hi","Good Morning"]});
> db.distinctAggregation.insertOne({"UserName":"Robert","UserPost":["Awesome"]});

Xem dữ liệu:

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

Tạo index trên trường mảng UserPost (tùy chọn, để tối ưu truy vấn):

> db.distinctAggregation.ensureIndex({"UserPost":1});

Lấy distinct values của trường UserPost:

> db.distinctAggregation.distinct("UserPost");

Kết quả:

[ "Awesome", "Good Morning", "Hello", "Hi" ]

Giải thích: MongoDB tự động "unwind" mảng khi dùng distinct() trên trường mảng, trả về tất cả giá trị duy nhất xuất hiện trong mảng đó qua các tài liệu.