mongodb入门-12更新2(二)
ml]
> db.test.update({_id:1},{$push:{ary:[6,7]}})
> db.test.find()
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ] ] }
实现上面的功能我们可以使用下面的$pushAll
$pushAll
将多个数值一次存入数组.
[html]
> db.test.update({_id:1},{$pushAll:{ary:[8,9]}})
> db.test.find()
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
$addToSet
与$push功能相同讲一个数字存入数组,不同的是如果数组中有这个数字,将不会插入,只会插入新的数据,同样也会有三种情况,与$push相同.
[html]
> db.test.find()
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
> db.test.update({_id:2},{$addToSet:{ary:7}}) -->ary中没有7,插入成功
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
{ "_id" : 2, "ary" : [ 6, 7 ], "text" : "test" }
> db.test.update({_id:2},{$addToSet:{ary:7}}) -->ary中有7,插入失败
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
{ "_id" : 2, "ary" : [ 6, 7 ], "text" : "test" }
其他的两种情况自己去测试.
$pop
删除数组最后一个元素
[html]
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
{ "_id" : 2, "ary" : [ 6, 7 ], "text" : "test" }
> db.test.update({_id:2},{$pop:{ary:1}})
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
$pull
删除数组中的一个元素,如果删除的字段不是数组,会报错
[html]
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 8, 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
> db.test.update({_id:1},{$pull:{ary:8}})
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
$pullAll
删除数组中的多个值,跟pushAll与push的关系类似.
[html]
> db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5, [ 6, 7 ], 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
> db.test.update({_id:1},{$pullAll:{ary:[1,2,8]}})
> db.test.find()
{ "_id" : 1, "ary" : [ 3, 4, 5, [ 6, 7 ], 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
$rename
为字段改名
[html]
> db.test.find()
{ "_id" : 1, "ary" : [ 3, 4, 5, [ 6, 7 ], 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
> db.test.update({_id:1},{$rename:{ary:"aryNew"}})
> db.test.find()
{ "_id" : 1, "aryNew" : [ 3, 4, 5, [ 6, 7 ], 9 ] }
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }