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

Lọc phần tử mảng trong MongoDB

Sử dụng toán tử $setIntersection kết hợp aggregation framework. Tạo collection:

> db.filterArrayElementsDemo.insertOne({ "Scores": [10,45,67,78,90,98,99,92] });
{ "acknowledged": true, "insertedId": ObjectId("5cd2d582b64f4b851c3a13c8") }

Hiển thị tài liệu

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

Kết quả:

{
    "_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
    "Scores": [10, 45, 67, 78, 90, 98, 99, 92]
}

Lọc mảng chỉ giữ các giá trị 10, 98, 99

> db.filterArrayElementsDemo.aggregate([
    { $match: { _id: ObjectId("5cd2d582b64f4b851c3a13c8") }},
    { $project: {
        Scores: { $setIntersection: ['$Scores', [10, 98, 99]] }
    }}
]);

Kết quả:

{ "_id": ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores": [10, 98, 99] }

Giải thích: $setIntersection trả về giao của hai mảng (phần tử xuất hiện ở cả hai). Thứ tự phần tử trong kết quả không đảm bảo.