Unset Operation¶
UnsetOperation đại diện cho stage $unset của MongoDB. Dùng để xoá một hoặc nhiều trường khỏi document hiện tại. Có thể truyền tên trường dạng string, Field (để map theo tên thật trong DB) hoặc AggregationExpression trả về tên trường cần xoá.
import { UnsetOperation } from 'red-aggregation/operations/unsetOperation';
import { Fields } from 'red-aggregation/aggregate/field';
Phương thức¶
Xoá một hoặc nhiều trường¶
// Xoá 1 trường
UnsetOperation.unset('deprecatedField').toDocument(context);
// => { $unset: 'deprecatedField' }
// Xoá nhiều trường (mảng tên)
UnsetOperation.unset('fieldA', 'fieldB').toDocument(context);
// => { $unset: ['fieldA', 'fieldB'] }
Hỗ trợ Field và AggregationExpression¶
// Truyền Field để map về tên thật trong DB
const field = Fields.field('aliasField', 'actualField');
new UnsetOperation([field]).toDocument(context);
// => { $unset: 'actualField' }
// Truyền AggregationExpression trả về tên trường cần xoá
const expr = { $concat: ['$first', '-', '$second'] }; // ví dụ expression
new UnsetOperation([expr as any]).toDocument(context);
// => { $unset: { $concat: ['$first', '-', '$second'] } }
Chain thêm trường với and(...)¶
UnsetOperation.unset('first')
.and('second')
.toDocument(context);
// => { $unset: ['first', 'second'] }
Lấy danh sách tên trường đã cấu hình xoá¶
const op = UnsetOperation.unset('first').and(Fields.field('alias', 'real'));
op.removedFieldNames();
// => ['first', 'real']
Lưu ý sử dụng¶
- Mảng
fieldskhông đượcnullvà không chứa phần tửnull. - Khi chỉ có 1 phần tử,
$unsetnhận string hoặc expression; khi nhiều phần tử,$unsetnhận mảng. - Với
Fieldhoặc string, tên field sẽ được map sangraw(ví dụ'user.name'→'user.name') bởicontext.