MongoDB uses the Insert () or Save () method to insert a document into the collection, with the following syntax:
Db. Collection_name.insert (document)
Example
The following documents can be stored in the Col collection of the MongoDB Runoob database:
>db.col.insert ({title: ' MongoDB Tutorial ',
Description: ' MongoDB is a Nosql database ' by
: ' Rookie tutorial ',
URL: '/http '/ Www.runoob.com ',
Tags: [' mongodb ', ' database ', ' NoSQL '],
likes:100
})
In the above example, Col is our collection name, and if the collection is not in that database, MongoDB automatically creates the set and inserts the document.
To view a document that has been inserted:
> Db.col.find ()
{"_id": ObjectId ("56064886ade2f21f36b03134"), "title": "MongoDB Tutorial", "description": "MongoDB is a A Nosql database "by": "Rookie Tutorial", "url": "Http://www.runoob.com", "tags": ["MongoDB", "Database", "NoSQL"], "likes": 100}
>
We can also define the data as a variable, as follows:
> document= ({title: ' MongoDB Tutorial ',
Description: ' MongoDB is a Nosql database ' by
: ' Rookie tutorial ',
URL: '/http '/ Www.runoob.com ',
Tags: [' mongodb ', ' database ', ' NoSQL '],
likes:100
});
After execution, the results are displayed as follows:
{
"title": "MongoDB Tutorial",
"description": "MongoDB is a Nosql database",
"by": "Rookie Tutorial",
"url": "Http://www.runo Ob.com ",
" tags ": [
" MongoDB ",
" database ",
" NoSQL "
],
" likes ":
To perform an insert operation:
> Db.col.insert (document)
Writeresult ({"ninserted": 1})
Insert document You can also use the Db.col.save command. If you do not specify the _id field, the Save () method is similar to the Insert () method. If the _id field is specified, the data for the _id is updated.
List of Notes
The following syntax can be used to insert a document after version 3.2:
Db.collection.insertone (): Inserts a document data into the specified collection
Db.collection.insertmany (): Inserts multiple document data into the specified collection
# Insert Single data > var document = Db.collection.insertOne ({"A": 3}) > Document {"acknowledged": true, " Insertedid ": ObjectId (" 571a218011a82a1d94c02333 ")} # Insert multiple data > var res = db.collection.insertMany ([{" B ": 3},