MongoDB insert document operation tutorial, mongodb document tutorial
? ? MongoDB uses the insert () or save () method to insert a document into the collection. The syntax is as follows:
db.COLLECTION_NAME.insert(document)
Instance
? ? The following documents can be stored in the col collection of the MongoDB runoob database:
> Db. col. insert ({title: 'mongodb ', description: 'mongodb is a Nosql database', by: 'cainiao ', url: 'https: // www.runoob.com ', tags: ['mongodb ', 'database', 'nosql'], likes: 100 })
? ? In the above example, col is our set name. If the set is not in the database, MongoDB will automatically create the set and insert the document.
? ? View the inserted document:
> Db. col. find () {"_ id": ObjectId ("56064886ade2f21f36b03134"), "title": "MongoDB tutorial", "description": "MongoDB is a Nosql Database ", "by": "cainiao tutorial", "url": "https://www.runoob.com", "tags": ["mongodb", "database", "NoSQL"], "likes ": 100}>
? ? We can also define the data as a variable, as shown below:
> Document = ({title: 'mongodb ', description: 'mongodb is a Nosql database', by: 'cainiao ', url: 'https: // www.runoob.com ', tags: ['mongodb ', 'database', 'nosql'], likes: 100 });
? ? The result is as follows:
{"Title": "MongoDB tutorial", "description": "MongoDB is a Nosql Database", "by": "cainiao tutorial", "url": "https://www.runoob.com ", "tags": ["mongodb", "database", "NoSQL"], "likes": 100}
? ? Perform the insert operation:
> db.col.insert(document)WriteResult({ "nInserted" : 1 })> ? ? You can also use the db. col. save (document) command to insert a document. If you do not specify the _ id field, the save () method is similar to the insert () method. If the _ id field is specified, the _ id data is updated.
Note list
? ? The following syntaxes can be used to insert a document after version 3.2:
? ? · Db. collection. insertOne (): inserts a document data entry into a specified set.
? ? · Db. collection. insertrecords (): inserts multiple pieces of document data into a specified set.
# Insert a single data entry> var document = db. collection. insertOne ({"a": 3})> document {"acknowledged": true, "insertedId": ObjectId ("571a218011a82a1d94c02333 ")} # insert multiple data records> var res = db. collection. insertMany ([{"B": 3 },{ 'C': 4}])> res {"acknowledged": true, "insertedIds ": [ObjectId ("571a22a911a82a1d94c02337"), ObjectId ("571a22a911a82a1d94c02338")]}