mongoDB基本操作(二)-(CRUD)

來源:互聯網
上載者:User

標籤:mongodb基本操作(二)-(crud

    MongoDB的shell操作資料,用到create、read、update、delete操作。

1、建立

    insert函數用於建立一個文檔到集合裡面。

    例,建立局部變數post,內容是代表文檔的JavaScript對象,裡面會有title、content和date幾個鍵。

> post = {"title":"My Blog Post",

... "content":"Here‘s my blog post",

... "date":new Date()}

{

        "title" : "My Blog Post",

        "content" : "Here‘s my blog post",

        "date" : ISODate("2015-02-02T05:04:55.861Z")

}

> db

test

    使用insert方法儲存到集合blog中,注意,這時blog並不存在。

> db.blog.insert(post)

WriteResult({ "nInserted" : 1 })

2、讀取

    find()函數會讀取集合中的所有文檔:

> db.blog.find();

{ "_id" : ObjectId("54cf05c00eb7b5f5718da826"), "title" : "My Blog Post", "conte

nt" : "Here‘s my blog post", "date" : ISODate("2015-02-02T05:04:55.861Z") }

    若是只想查看一個文檔,使用findOne()

> db.blog.findone();

2015-02-02T13:10:15.365+0800 TypeError: Property ‘findone‘ of object test.blog i

s not a function

> db.blog.findOne();

{

        "_id" : ObjectId("54cf05c00eb7b5f5718da826"),

        "title" : "My Blog Post",

        "content" : "Here‘s my blog post",

        "date" : ISODate("2015-02-02T05:04:55.861Z")

}

3、更新

    update接受至少兩個參數:一是更新文檔的限定條件,二是新的文檔。假設決定給先前寫的文章增加評論內容,則需要增加一個新的鍵,對應的值是存放評論的數組:

修改變數post,增加"comment"鍵:

> post.comments = [];

[ ]

執行update

> db.blog.update({"title":"My Blog Post"},post)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.blog.find();

{ "_id" : ObjectId("54cf05c00eb7b5f5718da826"), "title" : "My Blog Post", "conte

nt" : "Here‘s my blog post", "date" : ISODate("2015-02-02T05:04:55.861Z"), "comm

ents" : [ ] }

> db.blog.findOne();

{

        "_id" : ObjectId("54cf05c00eb7b5f5718da826"),

        "title" : "My Blog Post",

        "content" : "Here‘s my blog post",

        "date" : ISODate("2015-02-02T05:04:55.861Z"),

        "comments" : [ ]

}

4、刪除

    remove用來從資料庫中永久性地刪除文檔,在不適用參數進行調用的情況下,它會刪除一個集合內的所有文檔,也可以接受一個文檔以指定限制條件:

> db.blog.remove({"title":"My Blog Post"});

WriteResult({ "nRemoved" : 1 })

> db.blog.find();

>


mongoDB基本操作(二)-(CRUD)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.