MongoDB Query Language is used for CRUD operations to a MongoDB Database. CRUD stands for Create, Read, Update, Delete.
Query Language works with both MongoDB Compass and MongoDB Shell.
Prerequisites: JSON format knowledge, installed MongoDB Compass and Shell.
Let us consider this JSON string. This is a sample document in one collection about movie. You can see the value type of one field is flexible. An array does not have to contain elements in the same type. A document can contain nested documents.
{
"_id" :"5df0f5742f50210eea3d9857",
"title" : "Once Upon a Time in the West",
"year" : 1968,
"countries" : [
"Italy",
"USA",
"Spain",
{
"countryName" : "Vietnam"
},
{
"countryName" : "Thailand",
"region" : "Asia"
}
],
"genres" : [
"Western"
],
"writers" : [
"Sergio Donati",
"Sergio Leone",
"Dario Argento",
"Bernardo Bertolucci",
"Sergio Leone"
],
"imdb" : {
"id" : "tt0064116",
"rating" : 8.6,
"votes" : 201283
}
}
Tips: you can view, format, beautify JSON using this website: http://jsonviewer.stack.hu/
To use the below methods, you first need to
mongo "mongodb+srv://learningcluster-mntmv.mongodb.net/test" --username [myUserName]
show dbs
use [databaseName]
show collections
From now, the command shall follow this structure:
db.[collectionName].[methodName](param 1, param 2, ...)
.
where params are defined by particular method signatures.
In MongoDB Shell, after connecting to a collection, you can insert one document by typing this command:
db.[collectionName].insertOne({JSON param 1})
where param 1 is a new JSON document being inserted
ex: db.movieDetails.insertOne({"title":"Frozen 2","year":2019,"countries":["USA","Ireland"]})
If the operation succeed, the MongoDB Shell should return:
{
"acknowledged" : true,
"insertedId" : ObjectId("5df15d9d59dafddeaca090a5") <---- This is an unique ID for the created document
}
You can insert many documents at once with this command:
db.[collectionName].insertMany([JSON Array], {ordered : true/false})
where [JSON Array] is a new array containing many documents being inserted by this structure
[{document1}, {document2}, {document3}, ...]
{Ordered Param} is to decide to continue or stop inserting new documents if a run time error caused
true: stop inserting when encountering an error; false: continue inserting even encountering errors.
ex: db.movieDetails.insertMany([ {"title" : "Frozen 4"}, {"title" : "Enchanted"}, {"title" : "Brave"} ],{ordered:true})
// Square brackets indicate Array type