MongoDB insert document
In this chapter we will introduce to you how to insert data into a MongoDB 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, referred to as Binary JSON.
Insert documents
MongoDB uses the insert() or save() method to insert documents into the collection. The syntax is as follows:
db.COLLECTION_NAME.insert(document)
Instance
The following documents can Stored in the col collection of MongoDB's php database:
>db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'php中文网', url: 'http://www.php.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
In the above example, col is our collection name. We have already created it in the previous chapter. If the collection is not in the database, MongoDB will automatically create it. The collection is inserted into the document.
View the inserted document:
> db.col.find() { "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "php中文网", "url" : "http://www.php.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >
We can also define the data as a variable, as shown below:
> document=({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'php中文网', url: 'http://www.php.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 });
After execution The displayed result is as follows:
{ "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "php中文网", "url" : "http://www.php.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
Perform the insert operation:
> db.col.insert(document) WriteResult({ "nInserted" : 1 }) >
To insert a document, you can also use the db.col.save(document) command. If the _id field is not specified, the save() method is similar to the insert() method. If the _id field is specified, the data for that _id is updated.