Inserting Documents
In this section, you will learn to insert new documents into a MongoDB collection. MongoDB collections provide a function named insert()
, which is used to create a new document in a collection. The function is executed on the collection and takes the document to be inserted as an argument. The syntax of this function is shown in the next command:
db.collection.insert( <Document To Be Inserted>)
To see this in an example, open the mongo Shell, connect to the database cluster, and create a new database by using the use CH05
command. You can give a different name to the database as per your preference. The database mentioned in this command will be created if it is not present earlier. In the following operation, we are inserting a movie with a title
field and an _id
, and the output is printed on the next line:
> db.new_movies.insert({"_id" : 1, "title" : "Dunkirk"}) WriteResult({ "nInserted" : 1 })
Note...