更新操作
- 默认情况下,update只更新1条记录。特殊情况:multi: true
- 默认情况下,更新的匹配条件不满足,update就不做任何操作。特殊情况:upsert:true
//把item等与MNO2的记录,更新category,details属性,并把lastModified属性更新为当前时间
db.inventory.update(
{ item: "MNO2" },
{
$set: {
category: "apparel",
details: { model: "14Q3", manufacturer: "XYZ Company" }
},
$currentDate: { lastModified: true }
}
)
//更新嵌套属性
db.inventory.update(
{ item: "ABC1" },
{ $set: { "details.model": "14Q2" } }
)
//更新多条文档
db.inventory.update(
{ category: "clothing" },
{
$set: { category: "apparel" },
$currentDate: { lastModified: true }
},
{ multi: true }
)
//新item记录替换旧的,新记录包含旧id和新记录的属性
db.inventory.update(
{ item: "BE10" },
{
item: "BE05",
stock: [ { size: "S", qty: 20 }, { size: "M", qty: 5 } ],
category: "apparel"
}
)
//如果匹配就替换,不匹配就新插入一条文档
db.inventory.update(
{ item: "TBD1" },
{
item: "TBD1",
details: { "model" : "14Q4", "manufacturer" : "ABC Company" },
stock: [ { "size" : "S", "qty" : 25 } ],
category: "houseware"
},
{ upsert: true }
)
//如果匹配就做update操作,没有匹配就新插入一条文档
db.inventory.update(
{ item: "TBD2" },
{
$set: {
details: { "model" : "14Q3", "manufacturer" : "IJK Co." },
category: "houseware"
}
},
{ upsert: true }
)
删除操作
代码语言:javascript复制//删除集合内所有文档,但不删除索引
db.inventory.remove({})
//集合索引同时删除
db.inventory.drop()
//删除type属性匹配的文档
db.inventory.remove( { type : "food" } )
喜欢 (1)or分享 (0)