Sử dụng $match lọc bỏ null trước khi $group với $first.
Tạo collection
> db.conditionalFirstDemo.insertOne({_id: 100, "StudentName": "Chris", "StudentSubject": null});
{ "acknowledged": true, "insertedId": 100 }
> db.conditionalFirstDemo.insertOne({_id: 101, "StudentName": "Chris", "StudentSubject": null});
{ "acknowledged": true, "insertedId": 101 }
> db.conditionalFirstDemo.insertOne({_id: 102, "StudentName": "Chris", "StudentSubject": "MongoDB"});
{ "acknowledged": true, "insertedId": 102 }
> db.conditionalFirstDemo.insertOne({_id: 103, "StudentName": "Chris", "StudentSubject": "MongoDB"});
{ "acknowledged": true, "insertedId": 103 }
> db.conditionalFirstDemo.insertOne({_id: 104, "StudentName": "Chris", "StudentSubject": null});
{ "acknowledged": true, "insertedId": 104 }
Hiển thị tất cả
> db.conditionalFirstDemo.find();
Aggregation: lọc null rồi lấy $first
> db.conditionalFirstDemo.aggregate([
{ $match: { "StudentSubject": { $ne: null } } },
{ $group: { _id: "$StudentName", StudentSubject: { $first: "$StudentSubject" } } }
]);
Kết quả (lấy "MongoDB" — giá trị đầu tiên không null theo thứ tự _id):
{ "_id": "Chris", "StudentSubject": "MongoDB" }
Giải thích: $match loại bỏ tài liệu có StudentSubject: null. $group gom theo tên, $first lấy giá trị đầu tiên của nhóm (theo thứ tự tự nhiên của pipeline, thường là thứ tự _id).