# 字段更新运算符
运算符 | 含义 |
---|---|
$currentDate | 将字段的值设置为当前日期,可以是Date或Timestamp。 |
$inc | 按指定的数量增加字段的值 |
$min | 仅当指定的值小于现有字段值时才更新字段 |
$max | 仅当指定的值大于现有字段值时才更新字段 |
$mul | 将字段的值乘以指定的量 |
$rename | 重命名字段 |
$set | 设置文档中字段的值 |
$setOnInsert | 如果更新导致文档插入,则设置字段的值。对修改现有文档的更新操作没有影响 |
$unset | 从文档中删除指定的字段 |
###1、$currentDate当前日期运算符
例子:
{ _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }
操作:
使用$currentDate运算符对字段设为当前日期。
db.users.update(
{ _id: 1 },
{
$currentDate: {
lastModified: true,
"cancellation.date": { $type: "timestamp" }
},
$set: {
status: "D",
"cancellation.reason": "user request"
}
}
)
结果:
{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
"cancellation" : {
"date" : Timestamp(1410996356, 1),
"reason" : "user request"
}
}
###2、$inc增减运算符
例子:
{
_id: 1,
sku: "abc123",
quantity: 10,
metrics: {
orders: 2,
ratings: 3.5
}
}
运算:
使用$inc运算符对字段进行增减操作
db.products.update(
{ sku: "abc123" },
{ $inc: { quantity: -2, "metrics.orders": 1 } }
)
结果:
{
"_id" : 1,
"sku" : "abc123",
"quantity" : 8,
"metrics" : {
"orders" : 3,
"ratings" : 3.5
}
}
###3、$min保留小运算符
例子:
{ _id: 1, highScore: 800, lowScore: 200 }
运算:
$min指定值为150,150与lowScore比较,保留小的。
db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } )
结果:
{ _id: 1, highScore: 800, lowScore: 150 }
###4、$max保留大运算符
例子:
{ _id: 1, highScore: 800, lowScore: 200 }
运算:
谁大保留谁。
db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )
结果:
{ _id: 1, highScore: 950, lowScore: 200 }
###5、$mul乘法运算符
例子:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("10.99"), "qty" : 25 }
运算:
db.products.update(
{ _id: 1 },
{ $mul: { price: NumberDecimal("1.25"), qty: 2 } }
)
结果:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("13.7375"), "qty" : 50 }
###6、$rename重命名运算符
例子:
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
"nmae": { "first" : "george", "last" : "washington" }
}
运算:
db.students.updateMany( {}, { $rename: { "nmae": "name" } } )
结果:
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
"name": { "first" : "george", "last" : "washington" }
}
###7、$set字段设置运算符
例子:
{
_id: 100,
sku: "abc123",
quantity: 250,
instock: true,
reorder: false,
details: { model: "14Q2", make: "xyz" },
tags: [ "apparel", "clothing" ],
ratings: [ { by: "ijk", rating: 4 } ]
}
运算:
db.products.update(
{ _id: 100 },
{ $set:
{
quantity: 500,
details: { model: "14Q3", make: "xyz" },
tags: [ "coats", "outerwear", "clothing" ]
}
}
)
###8、$setOnInsert有就设值,没有就插入
db.products.update(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { defaultQty: 100 }
},
{ upsert: true }
)
###9、$unset删除字段运算符
删除sku值为"unknown"的quantity、instock字段
db.products.update(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } }
)