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

Đếm số phần tử mảng trong tài liệu MongoDB và hiển thị trường mới

Để đếm số phần tử trong mảng, sử dụng toán tử $size trong aggregation pipeline. Tạo collection với mảng môn học:

> db.demo703.insertOne({"ListOfSubject":["MySQL","MongoDB"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6ebaf551299a9f98c93b4") }
> db.demo703.insertOne({"ListOfSubject":["Java"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6ebb5551299a9f98c93b5") }
> db.demo703.insertOne({"ListOfSubject":["C","C++","Python"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6ebbf551299a9f98c93b6") }

Hiển thị dữ liệu:

> db.demo703.find();
{ "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"), "ListOfSubject" : [ "MySQL", "MongoDB" ] }
{ "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"), "ListOfSubject" : [ "Java" ] }
{ "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"), "ListOfSubject" : [ "C", "C++", "Python" ] }

Truy vấn aggregation đếm số phần tử và tạo trường mới:

> db.demo703.aggregate([
...   {$project: {NumberOfItemsInEachArray: {$size: "$ListOfSubject"}}}
... ]).pretty();

Kết quả:

{ "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"), "NumberOfItemsInEachArray" : 2 }
{ "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"), "NumberOfItemsInEachArray" : 1 }
{ "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"), "NumberOfItemsInEachArray" : 3 }

Ứng dụng: Kỹ thuật này hữu ích để thống kê, phân tích dữ liệu mảng như: số tag, số comment, số sản phẩm trong giỏ hàng, v.v.