码迷,mamicode.com
首页 > 数据库 > 详细

Mongdb操作嵌套文档

时间:2014-05-31 21:50:28      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

1、一个文档如下

db.posts.find()
bubuko.com,布布扣
{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!",
    "comments" : []
}
bubuko.com,布布扣

 

2、往_id等于"5388162dfc164ee1f39be37f"的文档中的comments插入数据

db.posts.update({"_id":ObjectId("5388162dfc164ee1f39be37f")},{$push:{"comments":{"content":"Good Article!","author":"Luxh"}}

 再插入一条

db.posts.update({"_id":ObjectId("5388162dfc164ee1f39be37f")},{$push:{"comments":{"content":"Not bad!","author":"Chuliuxiang"}}})

 结果如下

bubuko.com,布布扣
db.posts.find()


{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!",
    "comments" : [ 
        {
            "content" : "Good Article!",
            "author" : "Luxh"
        }, 
        {
            "content" : "Not bad!",
            "author" : "Chuliuxiang"
        }
    ]
}
bubuko.com,布布扣

 

3、根据内嵌文档查询

  1)查询出Luxh评论过的文章

bubuko.com,布布扣
db.posts.find({"comments.author":"Luxh"})

结果如下:
{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!",
    "comments" : [ 
        {
            "content" : "Good Article!",
            "author" : "Luxh"
        }, 
        {
            "content" : "Not bad!",
            "author" : "Chuliuxiang"
        }
    ]
}
bubuko.com,布布扣

  2)查询Luxh评论过的文章,返回指定的键

bubuko.com,布布扣
db.posts.find({"comments.author":"Luxh"},{"title":1,"content":1})

结果如下:

{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!"
}
bubuko.com,布布扣

  _id默认会返回。取消可设置"_id":0

 

4、修改

  将author=Luxh评论的内容content修改为"I like it!"

bubuko.com,布布扣
db.posts.update({"comments.author":"Luxh"},{$set:{"comments.$.content":"I like it!"}})

结果如下:
{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!",
    "comments" : [ 
        {
            "content" : "I like it!",
            "author" : "Luxh"
        }, 
        {
            "content" : "Not bad!",
            "author" : "Chuliuxiang"
        }
    ]
}
bubuko.com,布布扣

 

5、删除

  删除comments中author=Luxh的记录

bubuko.com,布布扣
db.posts.update({},{$pull:{"comments":{"author":"Luxh"}}})

结果如下:

{
    "_id" : ObjectId("5388162dfc164ee1f39be37f"),
    "title" : "Java Example",
    "content" : "This is a example for Java!",
    "comments" : [ 
        {
            "content" : "Not bad!",
            "author" : "Chuliuxiang"
        }
    ]
}
bubuko.com,布布扣

 

 

Mongdb操作嵌套文档,布布扣,bubuko.com

Mongdb操作嵌套文档

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/luxh/p/3760974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!