May 17, 2021 MongoDB
In this section, we'll show you how to insert data into the MongoDB collection.
The data structure of the document is basically the same as that of JSON.
All data stored in the collection is in BSON format.
BSON is a kind of json in a binary form of storage format, binary JSON for short.
MongoDB uses the insert() or save() method to insert documents into the collection, as follows:
db.COLLECTION_NAME.insert(document)
The following documents can be stored in mongoDB w3cschool.cn the col collection of the database:
>db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'w3cschool', url: 'http://www.w3cschool.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
In the example above, col is our collection name, which we've created in the previous section, and MongoDB automatically creates the collection and inserts the document if it's not in the database.
View inserted documents:
> db.col.find() { "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3cschool", "url" : "http://www.w3cschool.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >
We can also define the data as a variable, as follows:
> document=({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'w3cschool', url: 'http://www.w3cschool.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 });
The results after execution are as follows:
{ "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3cschool", "url" : "http://www.w3cschool.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
To perform an insert operation:
> db.col.insert(document) WriteResult({ "nInserted" : 1 }) >
You can also use the db.col.save command to insert a document. I f you do _id the field save() method is similar to the insert() method. If you specify _id field, the data for that _id is updated.