In this chapter, we will show you how to insert data into MongoDB's collection.
The data structure of the document is basically the same as JSON.
All data stored in the collection is in BSON format.
BSON is a binary storage format similar to json, called binary JSON for short.
Insert document
MongoDB uses the insert () or save () methods to insert documents into the collection. The syntax is as follows:
db。 COLLECTION_NAME.insert (document)
example
The following documents can be stored in the col collection of MongoDB's runoob database:
& gtdb.col.insert ({title:' MongoDB tutorial',
Description: "MongoDB is a Nosql database",
By: "rookie tutorial",
url:' ',
Tags: ['mongodb',' Database',' NoSQL'],
Like: 100
})
Col in the above example is our collection name, which we created in the previous chapter. If the collection is not in the database, MongoDB will automatically create the collection and insert the document.
View the inserted document:
& gtdb.col.find()
{"_ id": objectid ("56064886ade2f21f36b03134"), "title": "Tutorial of MongoDB", "description": "MongoDB is a database with Nosql", "by": "Tutorial for Beginners". "url": ","tags": ["mongodb ","database ","NoSQL"], "likes": 100}
& gt
We can also define data as variables, as follows:
& gtDocument=({title: 'MongoDB tutorial',
Description: "MongoDB is a Nosql database",
By: "rookie tutorial",
url:' ',
Tags: ['mongodb',' Database',' NoSQL'],
Like: 100
});
After execution, the display results are as follows:
{
"title": "MongoDB tutorial",
Description: MongoDB is a Nosql database.
"You": "Rookie Tutorial",
" url ":" ",
"Label": [
“mongodb”,
"database",
《NoSQL》
],
[Like]: 100
}
Perform an insert operation:
& gt database column insertion (document)
write result({ " n inserted ": 1 })
& gt
You can also use the command db.col.save(document) to insert a document. If the _id field is not specified, the save () method is similar to the insert () method. If the _id field is specified, the data of this _id will be updated.