Documents

Insérer un document

db.COLLECTION_NAME.insert({ json_document })

WriteResult({ "nInserted" : 1 })

Vérification des documents insérés

db.COLLECTION_NAME.find()

{ "_id" : ObjectId("5e972732d7b573ea12602de4"), "name" : "Username", "age" : 18 }

Insérer un tableau de document

// Création d'une variable contenant un tableau de document
var Allcourses =
[
{
Course: "Java",
details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
Batch: [ { size: "Medium", qty: 25 } ],
category: "Programming Language"
},
{
Course: ".Net",
details: { Duration: "6 months", Trainer: "Prashant Verma" },
Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
category: "Programming Language"
},
{
Course: "Web Designing",
details: { Duration: "3 months", Trainer: "Rashmi Desai" },
Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
category: "Programming Language"
}
];

db.COLLECTION_NAME.insert(Allcourses)

BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

Insertion de plusieurs documents avec Bulk

// Initialisation de la variable Bulk
var bulk = db.javatpoint.initializeUnorderedBulkOp();
// Création et insertions des documents
bulk.insert(
{
course: "java",
details: {
duration: "6 months",
Trainer: "Sonoo jaiswal"
},
Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
category: "Programming language"
}
);
bulk.execute()
// Résultat de sortie :
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})