操作符

操作符语法说明
$rename{ $rename: { <field1>: <newField1>,<filed2>:<newField2>,... } }字段重命名,字段若不存在.该文档不会发生改变.
$set{ $set: {<field1>,<value1>,...} }设置字段值,存在为更新字段.不存在为新增
$unset{ $unset: {<field1>:"", ...} }删除字段
$max{ $max: {<field1>: <value1>, <field2>: <value2>,...} }用value与字段的值进行比较.将key的值改为最大的.不存在时会创建值为value
$min{ $min: {<field1>: <value1>, <field2>: <value2>,...} }用value与字段的值进行比较.将key的值改为最小的.不存在时会创建值为value
$inc{ $inc: {<field1>: <value1>, <field2>: <value2>,...} }对值进行加减更改.当为负数时为减只试用于数字类型当key不存在时新建且值为value
$mul{ $mul: {<field1>: <value1>, <field2>: <value2>,...} }对值进行乘法运算只试用于数字类型.当key不存在时新建且值为0
$push{ $push: {<field1>:<value1>,<field1>:<value2>,...} }字段追加值.字段必须是数组类型.如果字段不存在会自动插入数组类型.如需要将插入的数组分多个值插入可结合$each使用
$pushAll{ $pushAll: {<field1>:<value1>,<field1>:<value2>,...} }同$push.可追加多个值到字段中.
$addToSet{ $addToSet: { <field1>: <value1>, <field2>: <value2>, ... } }向数组中追加元素,注意:不会像数组中添加重复的值,如添加值为数组或文档类型,必须完全相同(内容顺序),当插入数组类型的值会当成内嵌数组插入.`如需要将插入的数组分多个值插入可结合$each使用`
$pop{ $pop: { <field1>: <value1>,<field2>: <value2>,... } }删除数组内的第一个元素或最后一个元素语法中value为1(最后一个)或者-1(第一个)
$pull{ $pull: { <field1> : <value1>,<field2> : <value2>,...} }删除数组内值为value,value可以是指定值也可以是查询条件
$pullAll{ $pull: { <field1> : [<value1>,<value2>,...]<field2> :[<value1>,<value2>,...}, ... }同$pullAll,可删除多个值

Update

不使用更新操作符,update操作会更新整篇文档

使用update更新整片文档只会更新符合条件的第一条内容

说明

使用update修改文档, 命令格式为 `db.<collection>.update(<query>,<update>,<op>).

<query>: 更新文档的条件

<update>: 修改文档的内容:如不使用更新操作符则会替换成新的文档

<op>:

​ upsert: 如果不存在update的记录,是否插入新对象,true为插入,默认是false,不插入。当<query>条件精确(非区间匹配)插入的对象会包含<query>中的字段

​ multi: 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新

​ writeConcern: 抛出异常的级别。

示例

使用update替换文档

# 查询姓名为'gy'的文档
> db.qvbilam_user.find({ name: "gy" })
# 返回如下
{ "_id" : ObjectId("5f390b1ee9b6f99fc04f2b7b"), "name" : "gy", "num" : 12 }

# 使用update对文档进行替换
> db.qvbilam_user.update({name: "gy"},{cn_name: "二滑",num: 32})
# 返回nMatched:匹配数量, nUpserted:插入数量,nModified: 更新数量
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 通过主键id查询
> db.qvbilam_user.find({ _id: ObjectId("5f390b1ee9b6f99fc04f2b7b") })
# 文档内容被直接替换
{ "_id" : ObjectId("5f390b1ee9b6f99fc04f2b7b"), "cn_name" : "二滑", "num" : 32 }

尝试更改多条符合条件的文档:在之前提到过使用update更新文档只会更新符合条件的第一条内容.现在来测试一下是否能修改多条记录.

# 查询数量在12~14之间的文档
> db.qvbilam_user.find({ num: {$gt:12, $lt:14} })
{ "_id" : "qvbilam_01", "name" : "errorName", "num" : 13 }
{ "_id" : ObjectId("5f39049673936f515e5c0752"), "name" : "Cc", "num" : 13 }
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 13 }
{ "_id" : ObjectId("5f390671e9b6f99fc04f2b77"), "name" : "GuoTwo", "num" : 13 }
{ "_id" : ObjectId("5f390b1ee9b6f99fc04f2b7a"), "name" : "Coca cola", "num" : 13 }
{ "_id" : ObjectId("5f3d31f16dbe86c585d88d19"), "name" : "MoFan", "num" : 13, "location" : [ "China", "Hebei", "ShiJiaZhuang" ], "mobile" : 13211111111 }
# 使用相同的查询条件进行修改
db.qvbilam_user.update({num: {$gt:12, $lt:14}},{name: "hello13",num:13 ,explain: "qualified" })
# 可以看到更新的记录只有一条
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 再次查询12~14之间的文档
> db.qvbilam_user.find({ num: {$gt:12, $lt:14} })
{ "_id" : ObjectId("5f39049673936f515e5c0752"), "name" : "hello13", "num" : 13, "explain" : "qualified" }
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 13 }
{ "_id" : ObjectId("5f390671e9b6f99fc04f2b77"), "name" : "GuoTwo", "num" : 13 }
{ "_id" : ObjectId("5f390b1ee9b6f99fc04f2b7a"), "name" : "Coca cola", "num" : 13 }
{ "_id" : ObjectId("5f3d31f16dbe86c585d88d19"), "name" : "MoFan", "num" : 13, "location" : [ "China", "Hebei", "ShiJiaZhuang" ], "mobile" : 13211111111 }

$rename

- 字段重命名

# 将姓名为hello13文档的explain字段名更新为remark
> db.qvbilam_user.update({ name: "hello13" }, {$rename: {explain: "remark"}} )
# 返回修改结果
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 验证
> db.qvbilam_user.find({ name: {$eq: "hello13"} })
{ "_id" : ObjectId("5f39049673936f515e5c0752"), "name" : "hello13", "num" : 13, "remark" : "qualified" }

$set

- 设置字段值

# 将姓名为hello13文档的num值由13设置为23
> db.qvbilam_user.update({ name: "hello13" }, { $set: {num: 23} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 将姓名为hello13文档新增skill字段
> db.qvbilam_user.update({name: "hello13"}, {$set: {skill: "mongoDB"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 查询结果
> db.qvbilam_user.find({name:"hello13"})
{ "_id" : ObjectId("5f39049673936f515e5c0752"), "name" : "hello13", "num" : 23, "remark" : "qualified", "skill" : "mongoDB" }

修改数组字段需要将字段名和数组下标用引号包裹

# 创建包含数组,json 字段的文档
> db.qvbilam_user.insert({ name:"blue", num:21, mobile:[13212341234, 13512341234], skill: "{'mongoDB','Redis','MySQL' }"  })
# 修改手机号mobile数组里第二个值
> db.qvbilam_user.update({ name:"blue" }, {$set: {"mobile.1": 111111111111}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 验证
> db.qvbilam_user.find({ name: "blue"})
{ "_id" : ObjectId("5f47651d421e363aeb8901af"), "name" : "blue", "num" : 21, "mobile" : [ 13212341234, 111111111111 ], "skill" : "{'mongoDB','Redis','MySQL' }" }

修改数组字段需要将字段名和数组下标用引号包裹

# 演示文档的内容
> db.qvbilam_user.insert({
...   name: "red",
...     num: 13,
...     skill:{
...       work: "php",
...       like: "golang",
...       hate: "css"
...   }
... })
WriteResult({ "nInserted" : 1 })
# 修改skill文档里的hate为html
> db.qvbilam_user.update({ name: "red"}, {$set: {"skill.hate": "html"}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 验证
> db.qvbilam_user.find({name:"red"}).pretty()
{
    "_id" : ObjectId("5f4767d0421e363aeb8901b0"),
    "name" : "red",
    "num" : 13,
    "skill" : {
        "work" : "php",
        "like" : "golang",
        "hate" : "html"
    }
}

当更新的下标不存在时会创建.如果要更新的下标之前的下标也不存在会有null扩充

# 经过上述操作.mobile字段中有2个值13212341234, 111111111111
# 现在向第四个值增加一个手机号.即下标为3
> db.qvbilam_user.update({name: "blue"}, { $set: {"mobile.3": 6666} })
# 可以看到更新成功数量为1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 查看结果
> db.qvbilam_user.find({ name: "blue"}).pretty()
{
    "_id" : ObjectId("5f47651d421e363aeb8901af"),
    "name" : "blue",
    "num" : 21,
    "mobile" : [
        13212341234,
        111111111111,
        null,
        6666
    ],
    "skill" : "{'mongoDB','Redis','MySQL' }"
}

$unset

- 删除字段

字段后面的值无论传什么都是能把对应字段删除的.

# 将姓名为hello13的文档  skill,remark 删除
> db.qvbilam_user.update({ name: "hello13" }, {$unset: {skill: "",remark: ""} })

删除数组中的字段不会改变数组的长度

# 删除name为red的mobile字段的第一个值.即0下标
> db.qvbilam_user.update({ name: "blue" },{ $unset: {"mobile.0": ""} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 验证
> db.qvbilam_user.find({ name: "blue"}).pretty()
{
    "_id" : ObjectId("5f47651d421e363aeb8901af"),
    "name" : "blue",
    "num" : 21,
    "mobile" : [
        null,  # 被删除的元素
        111111111111,
        null,
        6666
    ],
    "skill" : "{'mongoDB','Redis','MySQL' }"
}

$max

- 字段的值与数对比,更新为两者最大的

# 将py的num=9 与 13进行对比
db.qvbilam_user.update({ name: "Py" }, { $max: { nun: 13 } })
# 更新数为1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 将py的num13 与 5进行对比
> db.qvbilam_user.update({ name: "Py" }, { $max: { nun: 5 } })
# 更新数为0
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

$min

- 字段的值与数对比,更新为两者最小的

# 将py的num=13 与 5进行对比
> db.qvbilam_user.update({ name: "Py" }, { $min: { nun: 5 } })
# 修改数量为0
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 结合max的操作查看结果
> db.qvbilam_user.find({ name: "Py"})
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 9, "nun" : 5 }

$inc

- 加减更新字段值

# 被更新文档
> db.qvbilam_user.find({name:"Py"})
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 13 }
# 对num进行减10
> db.qvbilam_user.update({ name:"Py" }, {$inc: {num: -10}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 查询结果
> db.qvbilam_user.find({name:"Py"})
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 3 }

$mul

- 乘法更新字段值

# 对原来的num 3 进行乘3 的操作
> db.qvbilam_user.update({ name: "Py" }, { $mul: { num: 3 } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 结果
> db.qvbilam_user.find({ name: "Py"})
{ "_id" : ObjectId("5f39049673936f515e5c0753"), "name" : "Py", "num" : 9 }

$push

- 向数组字段添加元素

# 查看被操作文档的内容
> db.qvbilam_user.find({ name: "hello13" })
{ "_id" : ObjectId("5f39049673936f515e5c0752"), "name" : "hello13", "num" : 23 }

# 向数组字段location添加QQ元素. 注意.在被操作的文档中是没有location这个字段的
> db.qvbilam_user.update({ name: "hello13" },{ $push: {location: {QQ: 534511019}} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 查看文档结果
> db.qvbilam_user.find({ name: "hello13" }).pretty()
{
    "_id" : ObjectId("5f39049673936f515e5c0752"),
    "name" : "hello13",
    "num" : 23,
    "location" : [
        {
            "QQ" : 534511019
        }
    ]
}

- 通过$each插入多个值

$position,$sort,$slice都需要结合$each执行,且执行顺序为$position,$sort,$slice

# 同$push的例子,使用向数组字段location中添加多个值
> db.qvbilam_user.update({name:"hello13"},{
...   $push: { location: {$each: [{"WeChat":"qvbilam"},{"E-mial":"qvbilam@163.com"}] } }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({name:"hello13"}).pretty()
{
    "_id" : ObjectId("5f39049673936f515e5c0752"),
    "name" : "hello13",
    "num" : 23,
    "location" : [
        {
            "QQ" : 534511019
        },
        {
            "WeChat" : "qvbilam"
        },
        {
            "E-mial" : "qvbilam@163.com"
        }
    ]
}

- 通过$each与$position将值插入到指定位置

# 通过$each与$position将值插入到指定位置
> db.qvbilam_user.update({name: "hello13"},
... {$push: {
...     location: {
...     $each: [{"mobile1": "13212341234"},{"mobile2": "13312341234"}],
...     $position: 0
...     }
...   } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({name:"hello13"}).pretty()
{
    "_id" : ObjectId("5f39049673936f515e5c0752"),
    "name" : "hello13",
    "num" : 23,
    "location" : [
        {
            "mobile1" : "13212341234"
        },
        {
            "mobile2" : "13312341234"
        },
        {
            "QQ" : 534511019
        },
        {
            "WeChat" : "qvbilam"
        },
        {
            "E-mial" : "qvbilam@163.com"
        }
    ]
}

- 通过$each与$sort对值进行排序

当sort值为1时正序,值为-1时倒序,插入后会对数组所有的值进行排序,并非对插入的值排序,

$sort不可单独使用.如果只想对原有的数据进行排序可以使用插入空的数据再排序,如:\$push:{字段 : {$each:[],$sort:-1}}

# 添加新的字段
> db.qvbilam_user.update({name:"save1"}, {$push : {music: {$each: [5,3,9]} } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 查看操作的文档music字段的值
> db.qvbilam_user.find({name:"save1"}).pretty()
{
    "_id" : ObjectId("5f3918c1e9b6f99fc04f2b7e"),
    "name" : "save1",
    "num" : 1,
    "music" : [
        5,
        3,
        9
    ]
}

# 对插入的值进行排序
> db.qvbilam_user.update({name: "save1"},
...   {$push: {
...     music:{
...       $each : [8,4],
...       $sort: 1
...     }
...   }
... } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 查询结果
> db.qvbilam_user.find({name:"save1"}).pretty()
{
    "_id" : ObjectId("5f3918c1e9b6f99fc04f2b7e"),
    "name" : "save1",
    "num" : 1,
    "music" : [
        3,
        4,
        5,
        8,
        9
    ]
}

通过$each与$sort对内嵌文档按照指定字段进行排序

# 对内嵌文档的字段进行排序 按照num正序排序
> db.qvbilam_user.update({name:"save1"},{
...   $push:{
...     music:{
...       $each: [{name:"hello1",num:11},{name:"hello2",num:10}],
...       $sort: {num: 1}
...     }
...   }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 查询结果
> db.qvbilam_user.find({name: "save1"}).pretty()
{
    "_id" : ObjectId("5f3918c1e9b6f99fc04f2b7e"),
    "name" : "save1",
    "num" : 1,
    "music" : [
        9,
        8,
        5,
        4,
        3,
        {
            "name" : "hello2",
            "num" : 10
        },
        {
            "name" : "hello1",
            "num" : 11
        }
    ]
}

$each结合\$slice对数组进行截取

并非对插入的数组进行截取,是对插入后的数组截取指定长度.

如果只想对原油的数组进行切割将$each设置为空即可。

# 插入2个值并对插入后的数组保留后4位
> db.qvbilam_user.update({name:"save1"},{
...   $push:{
...     music:{
...       $each: [3,2],
...       $slice: -4
...     }
...   }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({name: "save1"}).pretty()
{
    "_id" : ObjectId("5f3918c1e9b6f99fc04f2b7e"),
    "name" : "save1",
    "num" : 1,
    "music" : [
        {
            "name" : "hello2",
            "num" : 10
        },
        {
            "name" : "hello1",
            "num" : 11
        },
        3,
        2
    ]
}

$addToSet

- 向数组中添加元素

# 需要进行操作的数据
> db.qvbilam_user.find({ name: "MoFan" })
{ "_id" : ObjectId("5f3d31f16dbe86c585d88d19"), "name" : "MoFan", "num" : 13, "location" : [ "China", "Hebei", "ShiJiaZhuang" ], "mobile" : 13211111111 }

# 向文档中location数组字段添加元素 "ShenZe"
> db.qvbilam_user.update({ name: "MoFan" }, { $addToSet: {location: "ShenZe"} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({ name: "MoFan" })
{ "_id" : ObjectId("5f3d31f16dbe86c585d88d19"), "name" : "MoFan", "num" : 13, "location" : [ "China", "Hebei", "ShiJiaZhuang", "ShenZe" ], "mobile" : 13211111111 }

当添加的值为数组,文档类型.其内容必须完全不相同才会被插入

# 插入测试文档
> db.qvbilam_user.insert({ name: "wb", mum:24, location: ["China","HeBei","ShiJiaZhuang",{"QQ": 534511019, "WeChat": "qvbilam", "E-mail": "qvbilam@163.com" }] })
WriteResult({ "nInserted" : 1 })
# 查看文档
> db.qvbilam_user.find( {name: "wb"} ).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        }
    ]
}

向文档中contact数组字段添加相同顺序的文档内容测试

# 添加内容为 {"QQ" : 534511019,"WeChat" : "qvbilam","E-mail" : "qvbilam@163.com"}
> db.qvbilam_user.update({name: "wb"},{ $addToSet: {location: {"QQ" : 534511019,"WeChat" : "qvbilam","E-mail" : "qvbilam@163.com"} } })
# 返回结果修改为0
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

# 查询结果
> db.qvbilam_user.find({ name: "wb" }).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        }
    ]
}

向文档中contact数组字段添加不同顺数的文档内容测试

# 添加内容为 {"E-mail" : "qvbilam@163.com", "QQ" : 534511019, "WeChat" : "qvbilam"}
> db.qvbilam_user.update({name: "wb"}, {$addToSet: {location: {"E-mail" : "qvbilam@163.com", "QQ" : 534511019, "WeChat" : "qvbilam"}} })
# 修改结果数量为1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({ name: "wb" }).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        }
    ]
}

当插入数组类型的值会当成内嵌数组插入.如需要插入多个值可结合$each使用

插入内嵌数组

# 向数组location添加值["ShenZe","XiQu"] 结果为内嵌数组
> db.qvbilam_user.update({ name: "wb" },{ $addToSet: {location: ["ShenZe","XiQu"]} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 查询结果
> db.qvbilam_user.find({name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ]
    ]
}

通过$each将数组内多个值插入

# 结合$each向location数组添加值["DiJia","GaiYa"]. 
> db.qvbilam_user.update({ name: "wb" }, { $addToSet: { location : { $each: ["DiJia","GaiYa"] } } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 查询结果
> db.qvbilam_user.find({name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ],
        "DiJia",
        "GaiYa"
    ]
}

$pop

- 删除字段类型为数组的最后一个元素

# 删除文档location数组中的最后一个元素 GaiYa
> db.qvbilam_user.update({ name: "wb" },{ $pop: {location: 1} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 结果战士
> db.qvbilam_user.find({name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "China",
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ],
        "DiJia"
    ]
}

- 删除字段类型为数组的第一个一个元素

# 删除文档location数组中的最后一个元素 China
> db.qvbilam_user.update({ name: "wb" },{ $pop: {location: -1} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 结果展示
> db.qvbilam_user.find({name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ],
        "DiJia"
    ]
}

$pull

# 删除文档数组字段location中值为DiJia的内容
> db.qvbilam_user.update({ name: "wb" }, { $pull: {location: "DiJia"} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 查询结果
> db.qvbilam_user.find({ name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei",
        "ShiJiaZhuang",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ]
    ]
}

也可以使用正则.但不需要用到$elemMatch

# 删除location数组中包含ia的值
> db.qvbilam_user.update({ name: "wb" }, { $pull: { location: { $regex: /ia/ } } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 结果查询
> db.qvbilam_user.find({ name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        },
        [
            "ShenZe",
            "XiQu"
        ]
    ]
}

使用$pull删除内嵌数组指定的值

# 删除文档location数组字段内嵌数组里包含ShenZe的数组
> db.qvbilam_user.update({name: "wb"},{ $pull: {location: { $elemMatch: {$eq: "ShenZe"}}} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({ name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei",
        {
            "QQ" : 534511019,
            "WeChat" : "qvbilam",
            "E-mail" : "qvbilam@163.com"
        },
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        }
    ]
}

$pullAll

删除内嵌文档

# 删除文档数组类型location中的内嵌文档{"QQ" : 534511019,"WeChat" : "qvbilam","E-mail" : "qvbilam@163.com"}
> db.qvbilam_user.update({ name: "wb" },{ $pullAll: { location: [{"QQ" : 534511019,"WeChat" : "qvbilam","E-mail" : "qvbilam@163.com"}] } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.qvbilam_user.find({ name: "wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei",
        {
            "E-mail" : "qvbilam@163.com",
            "QQ" : 534511019,
            "WeChat" : "qvbilam"
        }
    ]
}

\$pullAll要比\$pull删除文档的值匹配的更精确

# 使用$pullAll现在要删除locaiton中内嵌文档中包含QQ为534511019的值
> db.qvbilam_user.update({name: "wb"},{ $pullAll: {location: [{"QQ":534511019}]} })
# 可以看到修改结果为0.
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

# 同样的使用$pull删除.删除条件相同
> db.qvbilam_user.update({name:"wb"},{ $pull: {location: {"QQ":534511019}} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果 - 内嵌文档直接被删除
> db.qvbilam_user.find({name:"wb"}).pretty()
{
    "_id" : ObjectId("5f50667f400b96ef2d251d6b"),
    "name" : "wb",
    "mum" : 24,
    "location" : [
        "HeBei"
    ]
}

Save

说明

save命令既可以插文档入也可以更新文档,当save中的参数包含_id字段,相当于执行了update(),同时upsert参数为true

示例

当文档存在时

# 要被修改的文档
> db.qvbilam_user.find({_id: ObjectId("5f50667f400b96ef2d251d6b")});
{ "_id" : ObjectId("5f50667f400b96ef2d251d6b"), "name" : "wb", "mum" : 24, "location" : [ "HeBei" ] }

# 通过_id 修改文档
> db.qvbilam_user.save({_id: ObjectId("5f50667f400b96ef2d251d6b"), name: "hello", location: ["ShanDong","JiNing"]});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 验证结果
> db.qvbilam_user.find({_id: ObjectId("5f50667f400b96ef2d251d6b")});
{ "_id" : ObjectId("5f50667f400b96ef2d251d6b"), "name" : "hello", "location" : [ "ShanDong", "JiNing" ] }

当文档不存在时

# 要被修改的文档 不存在
> db.qvbilam_user.find({_id: "ccc1996"})
>

# 执行
> db.qvbilam_user.save({_id: "ccc1996",name: "test"})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "ccc1996" })

# 验证
> db.qvbilam_user.find({_id: "ccc1996"})
{ "_id" : "ccc1996", "name" : "test" }
Last modification:February 20th, 2021 at 10:01 am