MongoDB Basics Tutorial For Beginners from Coding compiler. We started our journey to MongoDB by learning the basic workings of MongoDB. Of course, this is the core of learning MongoDB, and it can also help us answer questions such as which scenes MongoDB is suitable for.
MongoDB Basics Tutorial For Beginners
Before we started, there are six simple concepts that we need to know.
Related Article: What is MongoDB – MongoDB Tutorial For Beginners
- MongoDB
database
has the same concept as the “database” you know (schema for Oracle). In a MongoDB instance, there can be zero or more databases, each as a high-level container for storing data. - There can be zero or more
collections
(collections) in the database . Collections aretable
basically the same as in the traditional sense , you can simply think of the two as the same thing. - A collection is made up of zero or more
documents
(documents). Similarly, a document can be viewed as onerow
. - A document is composed of zero or more
fields
(fields). Yes, it iscolumns
. Indexes
(Indexes) play the same role in MongoDB as they do in RDBMS.Cursors
(Cursor) is different from the above five concepts, but it is very important and often overlooked, so I think they are worth discussing separately.
One of the most important things you should understand is that the cursor is, when you ask MongoDB to take the data, it will return a pointer to a result set instead of the actual data.
This pointer we call it cursor, we can take the cursor Do whatever we want, such as counting or spanning, without having to drag the real data down and operate on the real data.
om MongoDB, we pass the cursor
operation, and the read operation will be delayed until the actual data is needed.
So why do we need new terms (collection vs. table, document vs. row and field vs. column)? In order to make the look more complicated? In fact, although the concepts in these concepts are similar to those in relational data, there are still differences.
The core difference is that relational databases are table
defined above columns
, while document-oriented databases are document
defined above fields
. That is to say, collection
each of document
them can have its own independence fields
. Therefore, collection
it is a simplification table
, but document
one row
has more information than one .
Although these concepts are important, it doesn’t matter if you don’t understand them now. Inserting a few more data will understand what it means to say the above. Anyway, the point is that the collection does not strictly limit the storage content (so-called schema-less). Fields are tracked by each individual document. The advantages and disadvantages of doing so will be discussed in the following sections.
Ok, let’s get started. If you haven’t run MongoDB yet, go ahead and run the mongod
service and open the mongo shell. The shell uses JavaScript. You can try some global commands, such as help
or exit
. If you want to operate the current database, use db
, for example, db.help()
or db.stats()
.
If you want to manipulate a specified collection, in most cases we will manipulate the collection instead of the database db.COLLECTION_NAME
, such as db.unicorns.help()
or db.unicorns.count()
.
We continue, input db.help()
, and get a db
list of all the commands that can be executed.
By the way: Because this is a JavaScript shell, if the command you entered is missing ()
, you will see the source of the command instead of executing the command. I mention it, in order to avoid you executing the command that missed the brackets, and when you get a function (...){
return from the beginning, it is incredible. For example, if you type db.help
(without parentheses), you will see help
the internal implementation of the method.
First we use the global use
to switch the database, continue, input use learn
. Whether this database actually exists or not has nothing to do with it. When we generate a collection inside, the learn
database is automatically built. Now that we are in a database, you can start experimenting with database commands, for example db.getCollectionNames()
.
After execution, you will get an empty array ( [ ]
). Because the collection is modeless, we don’t need to configure it specifically. We can simply insert a document into a new collection. Like this, we use the insert
command to insert in the document:
db.unicorns.insert({name: 'Aurora',
gender: 'f', weight: 450})
This line of commands unicorns
executes the command on the collection insert
and passes in a parameter. MongoDB internally uses a binary serialization JSON format called BSON. External, that is to say we should use JSON in most cases, just like the parameters above.
Then we execute db.getCollectionNames()
and we will get two collections: unicorns
and system.indexes
. There will be a system.indexes
collection in each database that holds the index information for our data.
You can now unicorns
execute the find
command and then return to the list of documents:
db.unicorns.find()
Note that there will be one more field besides the field you specify _id
. Each document will have a unique _id
field. You can generate one yourself, or let MongoDB generate a ObjectId
type for you. In most cases, you will be happy to let MongoDB help you generate it. The default _id
field is already indexed – this explains why there is a system.indexes
collection. You can check out system.indexes
:
db.system.indexes.find()
You can see the name of the index, the database and collection being indexed, and the fields in the index.
Now, let’s return to our discussion about array modeless. To unicorns
insert a completely different document, for example:
db.unicorns.insert({name: 'Leto',
gender: 'm',
home: 'Arrakeen',
worm: false})
Then, use the find
listed documents again. When we understand a little deeper, we will discuss the interesting behaviour of MongoDB. Here, I hope that you begin to understand why those traditional terms are not applicable here.
MongoDB Basics – Master selector (Selector)
In addition to the six concepts we’ve covered, MongoDB has a practical concept to grasp before starting to discuss more in-depth topics: query selectors. MongoDB’s query selector is just like the one in the SQL statement where
. Therefore, you will use it when looking up, counting, updating, and deleting a collection’s documents.
A selector is a JSON object, the easiest is to {}
match all the documents. If we want to find out all the mother unicorns, we can use them {gender:'f'}
.
Before we start learning the selectors in depth, let’s make some preparations. First, unicorns
delete the data we just inserted into the collection, through: db.unicorns.remove({})
. Now, insert some data for the demo (you won’t call it):
db.unicorns.insert({name: 'Horny',
dob: new Date(1992,2,13,7,47),
loves: ['carrot','papaya'],
weight: 600,
gender: 'm',
vampires: 63});
db.unicorns.insert({name: 'Aurora',
dob: new Date(1991, 0, 24, 13, 0),
loves: ['carrot', 'grape'],
weight: 450,
gender: 'f',
vampires: 43});
db.unicorns.insert({name: 'Unicrom',
dob: new Date(1973, 1, 9, 22, 10),
loves: ['energon', 'redbull'],
weight: 984,
gender: 'm',
vampires: 182});
db.unicorns.insert({name: 'Roooooodles',
dob: new Date(1979, 7, 18, 18, 44),
loves: ['apple'],
weight: 575,
gender: 'm',
vampires: 99});
db.unicorns.insert({name: 'Solnara',
dob: new Date(1985, 6, 4, 2, 1),
loves:['apple', 'carrot',
'chocolate'],
weight:550,
gender:'f',
vampires:80});
db.unicorns.insert({name:'Ayna',
dob: new Date(1998, 2, 7, 8, 30),
loves: ['strawberry', 'lemon'],
weight: 733,
gender: 'f',
vampires: 40});
db.unicorns.insert({name:'Kenny',
dob: new Date(1997, 6, 1, 10, 42),
loves: ['grape', 'lemon'],
weight: 690,
gender: 'm',
vampires: 39});
db.unicorns.insert({name: 'Raleigh',
dob: new Date(2005, 4, 3, 0, 57),
loves: ['apple', 'sugar'],
weight: 421,
gender: 'm',
vampires: 2});
db.unicorns.insert({name: 'Leia',
dob: new Date(2001, 9, 8, 14, 53),
loves: ['apple', 'watermelon'],
weight: 601,
gender: 'f',
vampires: 33});
db.unicorns.insert({name: 'Pilot',
dob: new Date(1997, 2, 1, 5, 3),
loves: ['apple', 'watermelon'],
weight: 650,
gender: 'm',
vampires: 54});
db.unicorns.insert({name: 'Nimue',
dob: new Date(1999, 11, 20, 16, 15),
loves: ['grape', 'carrot'],
weight: 540,
gender: 'f'});
db.unicorns.insert({name: 'Dunx',
dob: new Date(1976, 6, 18, 18, 18),
loves: ['grape', 'watermelon'],
weight: 704,
gender: 'm',
vampires: 165});
Now that we have the data, we can start to learn to master the selector. {field: value}
Used to find documents whose field
values are equal value
. {field1: value1, field2: value2}
Equivalent to the and
query. Also $lt
, $lte
, $gt
, $gte
and $ne
are used to handle less than, less than or equal to, greater than, greater than or equal to, and not equal to the operation. For example, to get all the male horns weighing more than 700 pounds, we can do this:
db.unicorns.find({gender: 'm',
weight: {$gt: 700}})
//or (not quite the same thing, but for
//demonstration purposes)
db.unicorns.find({gender: {$ne: 'f'},
weight: {$gte: 701}})
$exists
Used to match whether a field exists, such as:
db.unicorns.find({
vampires: {$exists: false}})
A document will be returned. ‘$in’ is used to match whether the query document has a matching value in the array parameter we passed in, for example:
db.unicorns.find({
loves: {$in:['apple','orange']}})
Will return to those unicorns who like apple
or orange
.
If we want OR instead of AND to handle the selection condition, we can use the $or
operator and give it an array we want to match:
db.unicorns.find({gender: 'f',
$or: [{loves: 'apple'},
{weight: {$lt: 500}}]})
The above query will return to the female unicorn who likes apples
or is weigh
less than 500 pounds.
There is a very nice feature in our last two examples. You should have noticed that the loves
field is an array. MongoDB allows arrays to be treated as first class objects.
This is an incredible awesome feature. Once you start using it, you don’t know how to live without it. Most interestingly, array-based query becomes very simple: {loves: 'watermelon'}
the document will loves
have watermelon
the value of all check out.
In addition to the ones we have introduced, there are more operations available. All of this is documented in the Query Selectors chapter of the MongoDB manual . We are only talking about the things you need to learn, and the ones you use most often.
We have learned how the selector works with find
commands. I also introduced how to remove
use the count
command. Although the command is not introduced, you must know what to do, and update
then we will spend more time studying it in detail.
MongoDB _id
generated for our fields ObjectId
can be queried like this:
db.unicorns.find(
{_id: ObjectId("TheObjectId")})
Summary
We haven’t seen it yet update
, or we can use it to do more gorgeous things find
. However, we have already installed MongoDB and it is running, briefly introduced the commands andinsert
remove
commands (the full version is no more than what we introduced). We also introduced find
and learned about MongoDB selectors
. We have a good head and laid a solid foundation for future study.
Believe it or not, in fact, you have mastered most of the knowledge necessary to learn MongoDB – it is really easy to learn and use. I highly recommend that you try more and play more on this unit before continuing. Insert different documents, you can try to use different selectors in different collections. Try it find
, count
and remove
. After a few more trials, you will find that things that seem so out of place are actually used.