Get the App
SLTechnology News&Howtos  ›  Database  › 

[MongoDB Learning Notes 5] create, read, update, delete (CRUD) in MongoDB

Shulou Source: shulou.com Published: 2022-06-01 17:24:56 09月11日 Update

The database will be created (create), read (find), updated (update), deleted (remove), and MongoDB will also be used

First, create

Use the insert function to add documents to the collection. For example

Create the database blog and add the document to the collection post (first put the document in the variable of post)

> post= {"title": "My blog post", "context": "Here's my blog post", "date": new Date ()} > use blog switched to db blog > db.post.insert (post); WriteResult ({"nInserted": 1})

Second, read

Use the find method or the findone method to view the documents in the collection, such as

> db.post.find () {"_ id": ObjectId ("54a50253e287e09898eab58b"), "title": "My blog post", "context": "Here's my blog post", "date": ISODate ("2015-01-01T08:15:14.121Z")} > db.post.findOne () {"_ id": ObjectId ("54a50253e287e09898eab58b"), "title": "My blog post" Context: "Here's my blog post", "date": ISODate ("2015-01-01T08:15:14.121Z")} >

III. Update

Reassign the variable post

> use blog switched to db blog > post=db.post.findOne () {"_ id": ObjectId ("54a50253e287e09898eab58b"), "title": "My blog post", "context": "Here's my blog post", "date": ISODate ("2015-01-01T08:15:14.121Z")}

Add an comments document to the variable post

> post.comments = [] []

The update method updates the collection

> db.post.update ({"title": "My blog post"}, post) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne () {"id": ObjectId ("54a50253e287e09898eab58b"), "title": "My blog post", "context": "Here's my blog post", "date": ISODate ("2015-01-01T08:15:14.121Z") "comments": []}

IV. Delete

Delete a document with the removed method

> db.post.remove ({"title": "My blog post"}); WriteResult ({"nRemoved": 1}) > db.post.findOne (); null >

The post collection is empty after deletion

Tags: Documents methods updates variables data databases functions first notes learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Microsoft Shulou Technology Shulou Information Huawei