MongoDB fornisce insert() metodo (e altri due) per aggiungere documenti a un database.
MongoDB fornisce i seguenti tre metodi per inserire documenti in un database:
insert()insertOne()insertMany()
Il insert() Metodo
Il insert() inserisce uno o più documenti in una raccolta. Ogni documento è fornito come parametro. Il nome della raccolta è anteposto a insert() metodo.
Ecco la sintassi per inserire un singolo documento:
db.collectionName.insert({ name: "value" })
Nell'esempio sopra, il documento è composto da { name: "value" } . Questo è un documento JSON. I documenti JSON sono costituiti da una o più coppie nome/valore, racchiuse tra parentesi graffe {} .
MongoDB utilizza i documenti JSON per archiviare i dati, ecco perché inseriamo documenti in questo formato.
Abbiamo già utilizzato questo metodo in precedenza quando abbiamo creato un database.
Aggiungiamo un altro documento al nostro database:
db.artists.insert({ artistname: "Jorn Lande" })
Questo inserisce un documento con { artistname: "Jorn Lande" } come i suoi contenuti.
Ora, se cerchiamo gli artisti raccolta, vedremo due documenti (compreso quello che abbiamo creato in precedenza):
> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
Nota che MongoDB ha creato un _id campo per i documenti. Se non ne specifichi uno, MongoDB ne creerà uno per te. Tuttavia, puoi fornire questo campo durante l'inserimento se preferisci avere il controllo sul valore di _id campo.
db.artists.insert({ _id: 1, artistname: "AC/DC" }) Risultato:
> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }
Il _id fornito da MongoDB è un valore ObjectId a 12 byte. È composto dai seguenti valori;
- un valore di 4 byte che rappresenta i secondi dall'epoca di Unix,
- un identificatore di macchina a 3 byte,
- un ID processo a 2 byte e
- un contatore a 3 byte, che inizia con un valore casuale.
Crea più documenti
Puoi inserire più documenti all'interno di un singolo insert() metodo.
In questo esempio inseriamo tre documenti:
db.artists.insert(
[
{ artistname: "The Kooks" },
{ artistname: "Bastille" },
{ artistname: "Gang of Four" }
]
)
Si noti che i documenti vengono forniti come una matrice. I documenti sono racchiusi tra parentesi quadre [] , e sono separati da virgole.
L'esecuzione del codice precedente genera il seguente messaggio:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Documenti incorporati
Un documento può contenere altri documenti, matrici e matrici di documenti.
Puoi anche fornire più coppie nome/valore all'interno di un documento separandole con una virgola.
db.artists.insert({
artistname : "Deep Purple",
albums : [
{
album : "Machine Head",
year : 1972,
genre : "Rock"
},
{
album : "Stormbringer",
year : 1974,
genre : "Rock"
}
]
}) Risultato:
WriteResult({ "nInserted" : 1 })
Parametri
Il insert() accetta i seguenti parametri.
| Parametro | Tipo | Descrizione |
|---|---|---|
document | documento o array | Un documento o una matrice di documenti da inserire nella raccolta (come negli esempi precedenti). |
writeConcern | documento | Parametro facoltativo. Questo è un documento che esprime la preoccupazione per la scrittura. Un problema di scrittura descrive il livello di riconoscimento richiesto da MongoDB per le operazioni di scrittura su un mongod autonomo o su set di repliche o su cluster partizionati. |
ordered | booleano | Parametro facoltativo. Se il valore è impostato su true , MongoDB eseguirà un inserimento ordinato dei documenti nell'array e, se si verifica un errore con uno dei documenti, MongoDB restituirà senza elaborare i documenti rimanenti nell'array.
Se il valore è impostato su |
Il insertOne() Metodo
Puoi anche usare insertOne() metodo per inserire un singolo documento in una raccolta:
db.musicians.insertOne({ _id: 1, name: "Ian Gillan", instrument: "Vocals" })
Qui, abbiamo specificato una raccolta inesistente. Come con insert() metodo, la raccolta specificata verrà creata se non esiste già.
Noterai che l'output è diverso da quando usi insert() metodo:
{ "acknowledged" : true, "insertedId" : 1 }
Documenti incorporati
Come con insert() , puoi inserire documenti incorporati e array di documenti:
db.artists.insertOne({
artistname : "Miles Davis",
albums : [
{
album : "Kind of Blue",
year : 1959,
genre : "Jazz"
},
{
album : "Bitches Brew",
year : 1970,
genre : "Jazz"
}
]
}) Risultato:
{
"acknowledged" : true,
"insertedId" : ObjectId("578214f048ef8c6b3ffb0159")
}
Il insertMany() Metodo
Come suggerisce il nome, puoi usare insertMany() per inserire più documenti:
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 },
]
)
Di nuovo, l'output quando si utilizza insertMany() è diverso rispetto a se avessi inserito più documenti utilizzando insert() metodo:
{
"acknowledged" : true,
"insertedIds" : [
2,
3,
4,
5,
6,
7,
8
]
}
Documenti incorporati
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"
}
]
}
]) Risultato:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("578217c248ef8c6b3ffb015a"),
ObjectId("578217c248ef8c6b3ffb015b")
]
}