MongoDB's shell operation data, used to create, read, update, delete operations.
1. Create
The Insert function is used to create a document inside the collection.
example, create a local variable post, which is a JavaScript object representing the document, with the title, content, and date keys.
> 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
Use the Insert method to save to the collection blog, note that at this time the blog does not exist.
> Db.blog.insert (POST)
Writeresult ({"ninserted": 1})
2. Read
The Find () function reads all the documents in the collection:
> 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 ")}
If you want to view only one document, use 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
Update accepts at least two parameters: one is to update the document's qualifications, and the other is the new document. If you decide to add a comment to a previously written article, you need to add a new key, and the corresponding value is an array of comments:
Modify the variable post to add the "comment" key:
> post.comments = [];
[ ]
Perform an 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. Delete
Remove is used to permanently delete a document from the database and, in the case of non-applicable parameters, it deletes all documents within a collection, or it can accept a document to specify restrictions:
> Db.blog.remove ({"title": "My blog Post"});
Writeresult ({"nremoved": 1})
> Db.blog.find ();
>
MongoDB basic Operations (ii)-(CRUD)