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

Tổng hợp $slice để lấy phần tử tại vị trí chính xác từ mảng lồng nhau MongoDB

Sử dụng framework aggregation. Tạo collection:

> db.exactPositionDemo.insertOne({"StudentName":"John","StudentScores":[78,98,56,45,89]});
{ "acknowledged": true, "insertedId": ObjectId("5cd29a1c345990cee87fd883") }

Hiển thị tài liệu

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

Kết quả:

{
    "_id": ObjectId("5cd29a1c345990cee87fd883"),
    "StudentName": "John",
    "StudentScores": [78, 98, 56, 45, 89]
}

Trường hợp 1: Lấy 1 phần tử từ vị trí 0 (phần tử đầu)

> db.exactPositionDemo.aggregate([
    { "$project": { "StudentScores": { "$slice": ["$StudentScores", 0, 1] } }}
]);

Kết quả:

{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [78] }

Trường hợp 2: Lấy 1 phần tử từ vị trí 1 (phần tử thứ 2)

> db.exactPositionDemo.aggregate([
    { "$project": { "StudentScores": { "$slice": ["$StudentScores", 1, 1] } }}
]);

Kết quả:

{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [98] }

Cú pháp $slice: [$array, skip, limit] — bỏ qua skip phần tử đầu, lấy limit phần tử tiếp theo.