mongodb批量更新操作文档的数组键 (2)

> db.persons.update({_id:5},{$pop:{books:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ "java", "mongo" ] }
> db.persons.update({_id:5},{$pop:{books:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ "java" ] }

-1代表第一个元素,1代表最后一个元素

也可以使用pull命令一次删除一个指定的元素:

> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ "java", "mongo", "js" ] }
> db.persons.update({_id:5},{$pull:{books:"js"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ "java", "mongo" ] }

$pullAll命令可以一次指定多个要删除的元素:

> db.persons.update({_id:5},{$pullAll:{books:["java","mongo"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ ] }

创建一条新的记录_id为6:

> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ ] }
{ "_id" : 6, "books" : [ { "type" : "js", "name" : "extjs4.0" }, { "type" : "db"
, "name" : "mongodb" }, { "type" : "js", "name" : "jquery" } ] }

为type是js的books元素添加pens:"too long"属性,使用.符号一定使用双引号引用

> db.persons.update({"books.type":"js"},{$set:{"books.$.author":"tom"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4, "name" : "4" }
{ "_id" : 5, "books" : [ ] }
{ "_id" : 6, "books" : [ { "type" : "js", "name" : "extjs4.0", "author" : "tom"
}, { "type" : "db", "name" : "mongodb" }]
}

db.persons.update({"books.type":"js"},{$set:{"books.$.pens":"too long"}})

判断数组元素执行插入操作,重复的元素不会被插入第二次:

> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4 }
{ "_id" : 5, "books" : [ "js" ] }

> db.persons.update({_id:5},{$addToSet:{books:{$each:["js","db","java"]}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.persons.find()
{ "_id" : 2, "name" : "33" }
{ "_id" : 3, "name" : "33" }
{ "_id" : 4 }
{ "_id" : 5, "books" : [ "js", "db", "java" ] }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzffpf.html