About Me

header ads

MongoDB - Create a Document

MongoDB provides the insert() method (and two others) for adding documents to a database.
MongoDB provides the following three methods for inserting documents into a database:
  • insert()
  • insertOne()
  • insertMany()

The insert() Method

The insert() method inserts one or more documents into a collection. Each document is provided as a parameter. The collection name is prepended to the insert() method.
Here's the syntax for inserting a single document:
db.collectionName.insert({ name: "value" })
In the above example, the document consists of { name: "value" }. This is a JSON document. JSON documents consist of one or more name/value pairs, enclosed in curly braces {}.
MongoDB uses JSON documents to store data, so that's why we insert documents in this format.
We've already used this method previously when we created a database.
Let's add another document to our database:
db.artists.insert({ artistname: "Jorn Lande" })
This inserts a document with { artistname: "Jorn Lande" } as its contents.
Now, if we search the artists collection, we will see two documents (including the one we created previously):
> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
Note that MongoDB has created an _id field for the documents. If you don't specify one, MongoDB will create one for you. However, you can provide this field when doing the insert if you prefer to have control over the value of the _id field.
db.artists.insert({ _id: 1, artistname: "AC/DC" })
Result:
> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }
The _id that MongoDB provides is a 12-byte ObjectId value. It is made up of the following values;
  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

Create Multiple Documents

You can insert multiple documents within a single insert() method.
In this example, we insert three documents:
db.artists.insert(
   [
     { artistname: "The Kooks" },
     { artistname: "Bastille" },
     { artistname: "Gang of Four" }
   ]
)
Note that the documents are provided as an array. The documents are enclosed in square brackets [], and they are separated by commas.
Running the above code results in the following message:
BulkWriteResult({
 "writeErrors" : [ ],
 "writeConcernErrors" : [ ],
 "nInserted" : 3,
 "nUpserted" : 0,
 "nMatched" : 0,
 "nModified" : 0,
 "nRemoved" : 0,
 "upserted" : [ ]
})

Embedded Documents

A document can contain other documents, arrays, and arrays of documents.
You can also provide multiple name/value pairs within a document by separating them with a comma.
db.artists.insert({
    artistname : "Deep Purple",
    albums : [
                {
                    album : "Machine Head",
                    year : 1972,
                    genre : "Rock"
                }, 
                {
                    album : "Stormbringer",
                    year : 1974,
                    genre : "Rock"
                }
            ]
})
Result:
WriteResult({ "nInserted" : 1 })

Parameters

The insert() method accepts the following parameters.
ParameterTypeDescription
documentdocument or arrayA document or array of documents to insert into the collection (as in the above examples).
writeConcerndocumentOptional parameter. This is a document expressing the write concern. A write concern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters.
orderedbooleanOptional parameter. If the value is set to true, MongoDB will perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.
If the value is set to false, MongoDB will perform an unordered insert, and if an error occurs with one of documents, the remaining documents in the array will continue to be processed.

The insertOne() Method

You can also use the insertOne() method to insert a single document into a collection:
db.musicians.insertOne({ _id: 1, name: "Ian Gillan", instrument: "Vocals" })
Here, we've specified a non-existent collection. As with the insert() method, the specified collection will be created if it doesn't already exist.
You'll notice that the output is different to when you use the insert() method:
{ "acknowledged" : true, "insertedId" : 1 }

Embedded Documents

As with insert(), you can insert embedded documents and arrays of documents:
db.artists.insertOne({
    artistname : "Miles Davis",
    albums : [
                {
                    album : "Kind of Blue",
                    year : 1959,
                    genre : "Jazz"
                }, 
                {
                    album : "Bitches Brew",
                    year : 1970,
                    genre : "Jazz"
                }
            ]
})
Result:
{
 "acknowledged" : true,
 "insertedId" : ObjectId("578214f048ef8c6b3ffb0159")
}

The insertMany() Method

As the name suggests, you can use insertMany() to insert multiple documents:
db.musicians.insertMany(
   [
     { _id: 2, name: "Ian Paice", instrument: "Drums", born: 1948 },
     { _id: 3, name: "Roger Glover", instrument: "Bass", born: 1945 },
     { _id: 4, name: "Steve Morse", instrument: "Guitar", born: 1954 },
     { _id: 5, name: "Don Airey", instrument: "Keyboards", born: 1948 },
     { _id: 6, name: "Jeff Martin", instrument: "Vocals", born: 1969 },
     { _id: 7, name: "Jeff Burrows", instrument: "Drums", born: 1968 },
     { _id: 8, name: "Stuart Chatwood", instrument: "Bass", born: 1969 },
   ]
)
Again, the output when using insertMany() is different than if you'd inserted multiple documents using the insert() method:
{
 "acknowledged" : true,
 "insertedIds" : [
  2,
  3,
  4,
  5,
  6,
  7,
  8
 ]
}

Embedded Documents

db.artists.insertMany(
[
{
    artistname : "Robben Ford",
    albums : [
                {
                    album : "Bringing it Back Home",
                    year : 2013,
                    genre : "Blues"
                }, 
                {
                    album : "Talk to Your Daughter",
                    year : 1988,
                    genre : "Blues"
                }
            ]
}, {
    artistname : "Snoop Dogg",
    albums : [
                {
                    album : "Tha Doggfather",
                    year : 1996,
                    genre : "Rap"
                }, 
                {
                    album : "Reincarnated",
                    year : 2013,
                    genre : "Reggae"
                }
            ]
}
])
Result:
{
 "acknowledged" : true,
 "insertedIds" : [
  ObjectId("578217c248ef8c6b3ffb015a"),
  ObjectId("578217c248ef8c6b3ffb015b")
 ]
}

Post a Comment

0 Comments