MongoDB数组修改器更新数据
MongoDB数组修改器更新数据
这里,我们将了解一下数组修改器。数组,是我们经常看到和使用到的且非常有用的数据结构:它不仅可以通过索进行引用,还可以作为集合来使用。数组修改器,顾名思义,它是用来修改数组的,而不能用来修改整数或者字符串。数组修改器不多,就那么几个,但熟练掌握它后,将给我们带来非常方便的操作。下面,我们来了解一下:
> db.user.findOne()
{
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
}
]
}
以上是我的还在完善中的个人信息文档。假设最近我又交了一个好朋友,我想把他加到我的人际关系“relationships”数组中。这时,$push修改器就派上用场了。$push的作用就是,如果指定的键已经存在,它会向已有的数组末尾加入一个元素,要是没有就会创建一个新的数组。下面我们把新朋友加进去。
> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$push:{"relationships":{"fname":"xiong","lname":"lan"}}})
> db.user.findOne()
{
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
},
{
"fname" : "xiong",
"lname" : "lan"
}
]
}
有加就有减,那么怎么对数组进行“减”操作呢。能达到对数组“减”目的的修改器有两个,$pop和$pull。$pop和$pull又有区别,我们来分别实验。首先是$pop
> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$pop:{"relationships":1}})
> db.user.findOne()
{
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
}
]
}
从上面可以看出,它把我们刚加进去的朋友又删除了,也就是说它从数组的最后删除。那么,如果我们想从数组的开头删除该怎么办呢。很简单,把上面的“1”改成“-1”,它将逆向操作。下面看一下:
> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$pop:{"relationships":-1}})
> db.user.findOne()
{
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
}
]
}
从结果可以看出,它达到了我们预期的目的。那么如果我们想删除数组中间的呢。这时,$pull派上用场。首先,我们先将新朋友加进去,这里我不再演示。但我们可以想到“dongren”这个人是在数组的中间。现在