MongoDB tổng hợp chuyển đổi mảng thành chuỗi

Trang chủ Tài liệuHướng dẫn sử dụng MongoDB
$size (tổng hợp)
MongoDB tổng hợp chuyển đổi mảng thành chuỗi

Trên trang này

Show
  • Sự định nghĩa
  • Hành vi
  • Thí dụ

Sự định nghĩa

$size

Đếm và trả về tổng số phần tử trong một mảng.

$size có cú pháp như sau.

{ $size: <expression> }

Đối số cho $size có thể là bất kỳ

expression as long as it resolves to an array. For more information on expressions, see Expressions.

Hành vi

Đối số cho $size phải phân giải thành một mảng. Nếu đối số cho $size bị thiếu hoặc không phân giải thành một mảng, $size errors.

Thí dụ

Xem xét một bộ sưu tập

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }
0 với các tài liệu sau

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }

Thao tác đường dẫn tổng hợp sau đây sử dụng toán tử $size để trả về số lượng phần tử trong mảng

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }
2.

db.inventory.aggregate([   {      $project: {         item: 1,         numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }      }   }] )

Hoạt động trả về như sau

{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 }{ "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 }{ "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 }{ "_id" : 4, "item" : "ZZZ1", "numberOfColors" : "NA" }{ "_id" : 5, "item" : "ZZZ2", "numberOfColors" : "NA" }

←  $shift (tập hợp)$sin (tập hợp) →