mongodb增删改查之数组数据集使用

2,272次阅读
没有评论

共计 1515 个字符,预计需要花费 4 分钟才能阅读完成。

mongodb增删改查之数组数据集使用

之前的一篇文章介绍更新数组的操作,现在如果我们的文档中存在一个数组,后续向其中添加新的数据,我们要确保数组中的数据都是不存在重复的,也是构造一个set集合,那么可以借助$addToSet方法(尼玛这些方法的命名都是驼峰法)

看到这个方法的名字就知道保证数组集合是一个不存在重复的数据集,现在我们通过实际的操作来证明这个过程。

源数据集

{

    “_id” : ObjectId(“5afd34052c63ae1a943bdb27”),

    “name” : “hello”,

    “friends” : 34.0,

    “enemies” : 2.0,

    “favor” : [

        “2”,

        “3”,

        “4”,

        “5”,

        “6”,

        “7”,

        “8”,

        “9”,

        “10”,

        “1”

    ]

}

{

    “_id” : ObjectId(“5afd347c2c63ae1a943bdb29”),

    “name” : “joe”,

    “friends” : 34.0,

    “enemies” : 4.0

}

现在我们要向“favor”字段中添加新的数据

db.test.update({"name" : "hello"},{"addToSet":{"favor":{"each":["1","12"]}}})
得到的结果
{ 
    "_id" : ObjectId("5afd34052c63ae1a943bdb27"), 
    "name" : "hello", 
    "friends" : 34.0, 
    "enemies" : 2.0, 
    "favor" : [
        "2", 
        "3", 
        "4", 
        "5", 
        "6", 
        "7", 
        "8", 
        "9", 
        "10", 
        "1", 
        "12"
    ]
}
{ 
    "_id" : ObjectId("5afd347c2c63ae1a943bdb29"), 
    "name" : "joe", 
    "friends" : 34.0, 
    "enemies" : 4.0
}

现在我们学会了更改数组元素以及插入元素,当然我们也可以删除数组元素

db.test.update({"name" : "hello"},{"$pop":{"favor":1}})
数字为1表示从末尾开始删除元素,当为-1的时候是从开始删除数组的元素
结果如下所示
{ 
    "_id" : ObjectId("5afd34052c63ae1a943bdb27"), 
    "name" : "hello", 
    "friends" : 34.0, 
    "enemies" : 2.0, 
    "favor" : [
        "2", 
        "3", 
        "4", 
        "5", 
        "6", 
        "7", 
        "8", 
        "9", 
        "10", 
        "1"
    ]
}
{ 
    "_id" : ObjectId("5afd347c2c63ae1a943bdb29"), 
    "name" : "joe", 
    "friends" : 34.0, 
    "enemies" : 4.0
}

除了使用pop之外还可以通过pull基于某种条件的方式来删除数据,凡是符合条件的数据都会被删除
比如举个例子:
你的数组中包含两个“book1”,那么我们想要删除这个元素,那么这两个数据都会被删除掉

db.test.update({"name" : "hello"},{"$pull":{"favor":"5"}})
运行结果如下
{ 
    "_id" : ObjectId("5afd34052c63ae1a943bdb27"), 
    "name" : "hello", 
    "friends" : 34.0, 
    "enemies" : 2.0, 
    "favor" : [
        "2", 
        "3", 
        "4", 
        "6", 
        "7", 
        "8", 
        "9", 
        "10", 
        "1"
    ]
}
{ 
    "_id" : ObjectId("5afd347c2c63ae1a943bdb29"), 
    "name" : "joe", 
    "friends" : 34.0, 
    "enemies" : 4.0
}
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2018-05-19发表,共计1515字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码