Set Operation¶
SetOperation đại diện cho stage $set của MongoDB. Dùng để thêm/cập nhật một hoặc nhiều trường trong document hiện tại bằng literal, tham chiếu field, hoặc AggregationExpression.
import { SetOperation } from 'red-aggregation/operations/setOperation';
import { Fields } from 'red-aggregation/aggregate/field';
import { ArithmeticOperators } from 'red-aggregation/operator/arithmeticOperators/arithmeticOperators';
Phương thức¶
- SetOperation.createSetOperation(field, value)
- set(field).toValue(value) / set(field).toValueOf(exprOrField)
- set(field, value)
- and().set(...)
Tạo nhanh với createSetOperation¶
SetOperation.createSetOperation('name', 'John').toDocument(context);
// => { $set: { name: 'John' } }
// Chaining tiếp tục bổ sung trường
SetOperation.createSetOperation('age', 30)
.set('status', 'active')
.toDocument(context);
// => { $set: { age: 30, status: 'active' } }
Builder: set(field).toValue(...) / toValueOf(...)¶
// Gán literal
new SetOperation(new Map())
.set('score').toValue(10)
.toDocument(context);
// => { $set: { score: 10 } }
// Gán theo field khác
new SetOperation(new Map())
.set('total').toValueOf('amount')
.toDocument(context);
// => { $set: { total: '$amount' } }
// Gán theo AggregationExpression
const expr = ArithmeticOperators.add('$price').add('$tax');
new SetOperation(new Map())
.set('total').toValueOf(expr)
.toDocument(context);
// => { $set: { total: { $add: ['$price', '$tax'] } } }
Gán trực tiếp: set(field, value)¶
SetOperation.createSetOperation('name', 'Alice')
.set('age', 28)
.set('city', 'Hanoi')
.toDocument(context);
// => { $set: { name: 'Alice', age: 28, city: 'Hanoi' } }
Gán nhiều trường với and()¶
new SetOperation(new Map())
.set('firstName').toValue('John')
.and()
.set('lastName').toValue('Doe')
.toDocument(context);
// => { $set: { firstName: 'John', lastName: 'Doe' } }
Lưu ý sử dụng¶
set(field).toValueOf('otherField')sẽ tự map string thành'$otherField'quaFields.field/context.toValueOfchấp nhậnFieldhoặcAggregationExpressionvà sẽ gọitoDocument(context)khi cần.and()dùng để tiếp tục thêm các trường mới vào cùng một$setmà không làm mất các trường đã có.SetOperation.builder()trả vềFieldAppendergiúp gọi.set(...).toValue()/toValueOf()theo chuỗi.