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

Lấy độ dài các giá trị distinct trong mảng MongoDB

Để đếm số lượng giá trị distinct (duy nhất) trong mảng, kết hợp phương thức distinct() và thuộc tính .length.

Tạo collection:

> db.demo36.insertOne({"Names":["Chris","Bob"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e17643bcfb11e5c34d898d4") }
> db.demo36.insertOne({"Names":["Mike","Sam","Carol"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e176449cfb11e5c34d898d5") }
> db.demo36.insertOne({"Names":["Chris","Bob","David"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e17645bcfb11e5c34d898d6") }

Xem dữ liệu:

> db.demo36.find();
{ "_id" : ObjectId("5e17643bcfb11e5c34d898d4"), "Names" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e176449cfb11e5c34d898d5"), "Names" : [ "Mike", "Sam", "Carol" ] }
{ "_id" : ObjectId("5e17645bcfb11e5c34d898d6"), "Names" : [ "Chris", "Bob", "David" ] }

Lấy độ dài mảng distinct:

> db.demo36.distinct('Names').length;

Kết quả: 6 (Chris, Bob, Mike, Sam, Carol, David)

Giải thích:

  • distinct('Names'): Trả về mảng các giá trị duy nhất từ trường Names trên tất cả tài liệu
  • .length: Thuộc tính JavaScript trả về số phần tử của mảng

Lưu ý: distinct hoạt động trên toàn collection, không phải trên từng tài liệu riêng lẻ.