MongoDB修改器的使用1

为什么要使用修改器? 

   通常我们只会修改文档的一部分,这时候更新整个文档就显得很麻烦,通常是通过原子性的更新修改器来完成。

1."$set"修改器

   "$set"用来指定某个字段,如果不存在,则创建。这对部分更新或者添加来说就非常方便了。

如:

 step1:往users数据库长如一条数据,通过JavaScript来完成:

   var logs={name:"joe",age:30,sex:"female",location:"Wisconsin"}

   logs

 运行:

1 /* 1 */
2 {
3     "name" : "joe",
4     "age" : 30.0,
5     "sex" : "female",
6     "location" : "Wisconsin"
7 }

step2:放入users数据库

  db.users.insert(logs)

查询结果:

  db.users.find()

/* 1 */
{
    "_id" : ObjectId("575a2acfbc9fb3f12145a004"),
    "name" : "joe",
    "age" : 30.0,
    "sex" : "female",
    "location" : "Wisconsin"
}

step3:加入要插入一条喜欢的书籍:

db.users.update({name:"joe"},{"$set":{"favorite book":"War and Peace"}})

然后查询db.users.find()

/* 1 */
{
    "_id" : ObjectId("575a2acfbc9fb3f12145a004"),
    "name" : "joe",
    "age" : 30.0,
    "sex" : "female",
    "location" : "Wisconsin",
    "favorite book" : "War and Peace"
}

从结果总可以看出,数据中添加了一条favorite book字段,达到了我们想要的结果^_^;

step4:如果joe喜欢另一本书,继续来看"$set"如何大发神威;

 

/* 1 */
{
    "_id" : ObjectId("575a2acfbc9fb3f12145a004"),
    "name" : "joe",
    "age" : 30.0,
    "sex" : "female",
    "location" : "Wisconsin",
    "favorite book" : "forrest gump"
}

 

"$Set"还可以修改键的类型,比如喜欢的是好多书,就可以放在数组中。

如下:

 db.users.update({name:"joe"},{"$set":{"favorite book":["cat's Cradle","Foundation Trilogy","Ender's Game"]}})

/* 1 */
{
    "_id" : ObjectId("575a2acfbc9fb3f12145a004"),
    "name" : "joe",
    "age" : 30.0,
    "sex" : "female",
    "location" : "Wisconsin",
    "favorite book" : [ 
        "cat's Cradle", 
        "Foundation Trilogy", 
        "Ender's Game"
    ]
}

还可以通过"$unset"来操作删除某个字段

db.users.update({name:"joe"},{"$unset":{"favorite book":1}})

/* 1 */
{
    "_id" : ObjectId("575a2acfbc9fb3f12145a004"),
    "name" : "joe",
    "age" : 30.0,
    "sex" : "female",
    "location" : "Wisconsin"
}

这样就和最开始一样了。

"$set"还可以修改内嵌的文档

如:

var log={title:"A Blog Post",content:"...",author:{name:"joe",email:"joe@qq.com"}}
log
db.blog.posts.insert(log)
db.blog.posts.findOne()

/* 1 */
{
    "_id" : ObjectId("575a313fbc9fb3f12145a008"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe",
        "email" : "joe@qq.com"
    }
}

db.blog.posts.update({"author.name":"joe"},{"$set":{"author.name":"joe Mather"}})

/* 1 */
{
    "_id" : ObjectId("575a313fbc9fb3f12145a008"),
    "title" : "A Blog Post",
    "content" : "...",
    "author" : {
        "name" : "joe Mather",
        "email" : "joe@qq.com"
    }
}

总结:$开头的修改器都是通过主键key来修改对应的内容。

 

 

   

posted @ 2016-06-10 11:26  霓羽决奕  阅读(308)  评论(0编辑  收藏  举报