MongoDB 创建,更新和删除文档

插入并保存文档

可以使用insert方法想目标集合插入一个文档: > db.foo.insert({"bar": "baz"}) ,这个操作会给文档自动添加一个“_id”(如果原来没有的话),然后将其保存到MongoDB中。

批量插入

如果要想集合中插入多个文档,使用批量插入会更加快一点。使用批量插入,可以将一组文档传递给数据库。insert 也可以批量插入

> db.foo.Insert([{"_id": 0}, {"_id": 1}, {"_id": 2}])

删除文档

现在数据库中有些数据,要删除它:

 > db.foo.remove({}) 

上述命令会删除foo集合中所有的文档。但是不会删除集合本身,也不会删除集合的元信息。 db.tester.drop() 会把整个集合都被删除,所有数据都不见了。

更新文档

文档替换

最简单的更新使用一个新的文档完全替换匹配的文档。这适用于进行大规模模式迁移的情况。

> var joe = db.test.findOne({"name": "joe"})
> joe.relationships = {"friends": joe.friends, "enemies": joe.enemies}
{ "friends" : 32, "enemies" : 2 }
> joe.username = joe.name
joe
> delete joe.friends
true
> delete joe.enemies
true
> delete joe.name
true
> db.test.update({"name": "joe"}, joe)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

使用修改器

通常文档只会有一部分要更新。可以使用原子性的更新修改器,指定对文档中的某些字段进行更新。更新修改器是一种特殊的键,用来指定复杂的更新操作,比如修改,增加或者删除键,还可能是操作数组或者内嵌文档。

$inc 

增加计数器,原子性的完成这个增加

> db.analytics.findOne()
{
    "_id" : ObjectId("5ccd9315fa7a6f5af4645efa"),
    "url" : "www.example.com",
    "pageviews" : 20
}
> db.analytics.update({"url": "www.example.com"}, {"$inc": {"pageviews": 1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.analytics.findOne() { "_id" : ObjectId("5ccd9315fa7a6f5af4645efa"), "url" : "www.example.com", "pageviews" : 21 }

使用修改器时,“_id”的值不能改变。(整个文档替换是可以改变)其他键值,包括其他唯一索引的键,都是可以更改的。

$set

用来制定一个字段的值。如果这个字段不存在就创建他。这对更新模式或者增加用户定义的键来说非常方便。

> db.users.findOne()
{
    "_id" : ObjectId("5ccd954b7dd247457f95a420"),
    "name" : "joe",
    "age" : 30,
    "sex" : "male",
    "location" : "shanghai",
    "favourite book" : "War and Peace"
}
> db.users.update({"_id": ObjectId("5ccd954b7dd247457f95a420")}, {"$set": {"favourite book": "Green Eggs and Ham"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne()
{
    "_id" : ObjectId("5ccd954b7dd247457f95a420"),
    "name" : "joe",
    "age" : 30,
    "sex" : "male",
    "location" : "shanghai",
    "favourite book" : "Green Eggs and Ham"
}
> db.users.update({"_id": ObjectId("5ccd954b7dd247457f95a420")}, {"$set": {"favourite book": ["Green Eggs and Ham", "War and Peace"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne()
{
    "_id" : ObjectId("5ccd954b7dd247457f95a420"),
    "name" : "joe",
    "age" : 30,
    "sex" : "male",
    "location" : "shanghai",
    "favourite book" : [
        "Green Eggs and Ham",
        "War and Peace"
    ]
}

可以用来修改值,也可以用来修改值的类型。

如果想删除一个键可以使用 $unset

> db.users.update({"_id": ObjectId("5ccd954b7dd247457f95a420")}, {"$unset": {"favourite book": 1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne()
{
    "_id" : ObjectId("5ccd954b7dd247457f95a420"),
    "name" : "joe",
    "age" : 30,
    "sex" : "male",
    "location" : "shanghai"
}

用$set修改内嵌文档

{
    "_id" : ObjectId("5ccd977c7dd247457f95a421"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe",
        "email" : "[email protected]"
    }
}
> db.blog.posts.update({"author.name": "joe"}, {"$set": {"author.name": "joe schmoe"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.posts.findOne()
{
    "_id" : ObjectId("5ccd977c7dd247457f95a421"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe schmoe",
        "email" : "[email protected]"
    }
}

如果不用$修改器那么:

db.blog.posts.update({"title": "A Blog Post"}, {"content": "11111"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.posts.find()
{ "_id" : ObjectId("5ccd977c7dd247457f95a421"), "content" : "11111" }
{ "_id" : ObjectId("5ccd98487dd247457f95a422"), "title" : "A Blog Post 022222", "content" : "...", "author" : { "name" : "joe", "email" : "[email protected]" } }

整个文档会一起被替换掉。

数组修改器

添加元素:$push

> db.blog.posts.findOne()
{
    "_id" : ObjectId("5ccd977c7dd247457f95a421"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe",
        "email" : "[email protected]"
    }
}
> db.blog.posts.update({"_id" : ObjectId("5ccd977c7dd247457f95a421")}, {"$push": {"comment": {"name": "joe", "email": "[email protected]", "content": "very good"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.posts.findOne()
{
    "_id" : ObjectId("5ccd977c7dd247457f95a421"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe",
        "email" : "[email protected]"
    },
    "comment" : [
        {
            "name" : "joe",
            "email" : "[email protected]",
            "content" : "very good"
        }
    ]
}

如果还想要加一条评论,继续使用$push

> db.blog.posts.update({"_id" : ObjectId("5ccd977c7dd247457f95a421")}, {"$push": {"comment": {"name": "bob", "email": "[email protected]", "content": "very bad"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.posts.findOne()
{
    "_id" : ObjectId("5ccd977c7dd247457f95a421"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe",
        "email" : "[email protected]"
    },
    "comment" : [
        {
            "name" : "joe",
            "email" : "[email protected]",
            "content" : "very good"
        },
        {
            "name" : "bob",
            "email" : "[email protected]",
            "content" : "very bad"
        }
    ]
}

如果要多条插入可以配合使用$each

> db.stock.ticker.update({"_id": 1}, {"$push": {"hourly": {"$each": [555, 666, 777]}}})

这样就可以将三个新元素添加到数组中。如果只有一个那么相当于没有使用$each,只是简单的$push操作。

$slice

还可以在添加数组时限制长度,可以使用 $slice 这样可以得到一个最多包含N个元素的数组

> db.blog.posts.update({"title": "A Blog Post"}, {"$push": {"comment": {"$each": [{"1": "a"},{"2": "b"},{"3": "c"},{"7": "d"},{"6": "f"}], "$slice": -2}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.blog.posts.find()
{ "_id" : ObjectId("5ccd977c7dd247457f95a421"), "title" : "A Blog Post", "content" : "...", "author" : { "name" : "joe", "email" : "[email protected]" }, "comment" : [ { "7" : "d" }, { "6" : "f" } ] }> db.blog.posts.update({"title": "A Blog Post"}, {"$push": {"comment": {"$each": [{"1": "a"},{"2": "b"},{"3": "c"},{"7": "d"},{"6": "f"}], "$slice": -10}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.blog.posts.find()
{ "_id" : ObjectId("5ccd977c7dd247457f95a421"), "title" : "A Blog Post", "content" : "...", "author" : { "name" : "joe", "email" : "[email protected]" }, "comment" : [ { "7" : "d" }, { "6" : "f" }, { "1" : "a" }, { "2" : "b" }, { "3" : "c" }, { "7" : "d" }, { "6" : "f" } ] }

可以看到当$slice为-2时会添加 最后两个值并且覆盖原来的值,$slice的值必须是负整数。

$sort

排序

db.blog.posts.update({"title": "A Blog Post"}, {"$push": {"comment": {
              "$each": [{"1": "a", "rating": 6.6},{"2": "b", "rating": 7.9},{"3": "c", "rating": 9.0}],
              "$slice": -10,
              "$sort": {"rating": -1}}}})

这样会根据"rating"字段的值对数组中所有的对象进行排序, "$slice","$sort"必须与"$push"配合使用

将数组作为数据集使用,避免重复

如果想将数组作为数据集使用,保证数组内的元素不会重复。可以在查询文档中使用"$ne"来实现,例如 如果作者不在文档中那么就添加进去可以这么做

> db.papers.update({"authors cited": {"$ne": "Richie"}},
...  {"$push": {"authors cited": "Richie"}})

也可以使用 $addToSet 因为有时候$ne行不通

用法和$push相当 也可以搭配 $each使用 但是 $addToSet 可以避免添加重复的值

删除数组中的元素

$pop $pull

{"$pop": {"key": 1}}  // 从末尾删除
{"$pop": {"key": -1}}  //从头部删除

有时候需要基于特定的条件来删除元素,而不仅仅是一句元素的位置这时候可以使用 $pull 例如有一个无序的待完成事项列表:

> db.lists.insert({"todo": ["dishes", "laundry", "dry cleaning"]})

如果我们完成了洗衣服可以用下面方式完成它

> db.lists.update({}, {"$pull": {"todo": "laundry"}})

upsert

如果我们有一个需求,如果没有文档那么就创建他,如果存在了我们就在特定字段上 +1 具体写法如下

> db.users.update({"url": "/blog"}, {"$inc": {"pageviews": 1}}, true )

最后一个参数就是他的开关

更新多个文档,那么只要update的第四个参数设置为true就可以了

findAndModify

使用

ps = db.runCommand({"findAndModify": "processes",
                                  "query": {"status": "READY"},
                                  "sort": {"priority": -1},
                             "update": {"$set": {"status": "RUNNING"}}}).value
do_something(ps)                
  • findAndModify
    字符串,集合名
  • query
    查询文档,用于检索文档的条件
  • sort
    排序结果的条件
  • update
    修改器文档(update和remove必须选一个)
  • new
    布尔类型,表示返回更新前的文档还是更新后的文档,默认更新前
  • fields
    文档中需要返回的字段(可选)
  • upsert
    布尔类型,值为true是表示这是一个upsert.默认为false

猜你喜欢

转载自www.cnblogs.com/Stay-J/p/10810078.html