MongoDB_02
MongoDB_02
Attribution: MongoDB: The Definitive Guide, Third Edition by Shannon Bradshaw, Eoin Brazil, and Kristina Chodorow (O’Reilly). Copyright 2020 Shannon Bradshaw and Eoin Brazil, 978-1-491-95446-1.
Getting and Starting MongoDB
Install MongoDB Community Edition on Windows
For detailed information on installing MongoDB on your system, see the appropriate installation tutorial in the MongoDB documentation.
The following contents are all executed in Windows environment.
Introduction to the MongoDB Shell
MongoDB comes with a JavaScript shell (Mongosh) that allows interaction with a MongoDB instance from the command line. The shell is useful for performing administrative functions, inspecting a running instance, or just exploring MongoDB.
The mongosh is a crucial tool for using MongoDB. We’ll use it extensively throughout the rest of the text.
Running the Shell
To start the shell, run the mongo executable:
> mongosh
Enter a MongoDB connection string (Default: mongodb://localhost/)
The shell is a full-featured JavaScript interpreter, capable of running arbitrary JavaScript programs.
e.g.
> x=200
200
> x/5
40
We can also leverage all of the standard JavaScript libraries:
> Math.sin(Math.PI/2)
1
> new Date("2024/7/28");
ISODate('2024-07-27T16:00:00.000Z')
> "Hello, World!".replace("World", "MongoDB");
Hello, MongoDB!
We can even define and call JavaScript functions:
> function factorial (n) {
... if (n <= 1) return 1;
... return n * factorial(n - 1);
... }
> factorial(5);
120
Note that you can create multiline commands. The shell will detect whether the JavaScript statement is complete when you press Enter. If the statement is not complete, the shell will allow you to continue writing it on the next line. Pressing Enter three times in a row will cancel the half-formed command and get you back to the >
prompt.
A MongoDB Client
Although the ability to execute arbitrary JavaScript is useful, the real power of the shell lies in the fact that it is also a standalone MongoDB client.
On startup, the shell connects to the test database on a MongoDB server and assigns this database connection to the global variable db. This variable is the primary access point to your MongoDB server through the shell.
To see the database to which db
is currently assigned, type in db
and hit Enter:
> db
test
The shell contains some add-ons that are not valid JavaScript syntax but were implemented because of their familiarity to users of SQL shells. The add-ons do not provide any extra functionality, but they are nice syntactic sugar.
For instance, one of the most important operations is selecting which database to use:
> use video
switched to db video
> db
video
And if you look at the db
variable, you can see that it refers to the video database.
Because this is a JavaScript shell, typing a variable name will cause the name to be evaluated as an expression. The value (in this case, the database name) is then printed.
You may access collections from the db
variable. e.g.
> db.movies
vedio.vedio
returns the movies collection in the current database. Now that we can access a collection in the shell, we can perform almost any database operation.
Basic Operations with the Shell
We can use the four basic operations, create, read, update, and delete (CRUD), to manipulate and view data in the shell.
CREATE
The insertOne
function adds a document to a collection.
For example, suppose we want to store a movie. First, we’ll create a local variable called movie that is a JavaScript object representing our document. It will have the keys "title
", "director
", and "year
" (the year it was released):
vedio> movie = {"title" : "Star Wars: Episode IV - A New Hope",
... "director" : "George Lucas",
... "year" : 1977}
{
"title" : "Star Wars: Episode IV - A New Hope",
"director" : "George Lucas",
"year" : 1977
}
This object is a valid MongoDB document, so we can save it to the movies collection using the insertOne
method:
vedio> db.vedio.movies.insertOne(movie)
{
acknowledged: true,
insertedId: ObjectId('66a7530b373ac8c6cbc4e49b')
}
The movie has been saved to the database. We can see it by calling find
on the collection:
vedio> db.vedio.movies.find().pretty()
[
{
_id: ObjectId('66a7530b373ac8c6cbc4e49b'),
title: 'Star Wars: Episode IV - A New Hope',
director: 'George Lucas',
year: 1977
}
]
We can see that an "_id"
key was added and that the other key/value pairs were saved as we entered them.
READ
find
and findOne
can be used to query a collection.
If we just want to see one document from a collection, we can use findOne
:
vedio> db.vedio.movies.findOne()
{
_id: ObjectId('66a7530b373ac8c6cbc4e49b'),
title: 'Star Wars: Episode IV - A New Hope',
director: 'George Lucas',
year: 1977
}
find
and findOne
can also be passed criteria in the form of a query document. This will restrict the documents matched by the query. The shell will automatically display up to 20 documents matching a find, but more can be fetched.
UPDATE
If we would like to modify our post, we can use updateOne
.
the first is the criteria to find which document to update, and the second is a document describing the updates to make.
Suppose we decide to enable reviews for the movie we created earlier. We’ll need to add an array of reviews as the value for a new key in our document.
To perform the update, we’ll need to use an update operator, set
:
vedio> db.vedio.movies.updateOne({title : "Star Wars: Episode IV - A New Hope"},
... {$set : {reviews: []}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
vedio> WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})
Now the document has a "reviews"
key. If we call find
again, we can see the new key:
vedio> db.vedio.movies.find().pretty()
[
{
_id: ObjectId('66a7530b373ac8c6cbc4e49b'),
title: 'Star Wars: Episode IV - A New Hope',
director: 'George Lucas',
year: 1977,
reviews: []
}
]
update operator, set
:
> db.movies.updateOne({title : "Star Wars: Episode IV - A New Hope"},
... {$set : {reviews: []}})
WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})
Now the document has a "reviews"
key. If we call find
again, we can see the new key:
> db.movies.find().pretty()
{
"_id" : ObjectId("5721794b349c32b32a012b11"),
"title" : "Star Wars: Episode IV - A New Hope",
"director" : "George Lucas",
"year" : 1977,
"reviews" : [ ]
}
See [“Updating Documents”](javascript:void(0)) for detailed information on updating documents.
DELETE
deleteOne
and deleteMany
permanently delete documents from the database.
Both methods take a filter document specifying criteria for the removal. For example, this would remove the movie we just created:
vedio> db.vedio.movies.deleteOne({title : "Star Wars: Episode IV - A New Hope"})
{ acknowledged: true, deletedCount: 1 }
Use deleteMany
to delete all documents matching a filter.
Data Types
The beginning of this chapter covered the basics of what a document is. Now that you are up and running with MongoDB and can try things in the shell, this section will dive a little deeper.
MongoDB supports a wide range of data types as values in documents. In this section, we’ll outline all the supported types.
Basic Data Types
Documents in MongoDB can be thought of as “JSON-like” in that they are conceptually similar to objects in JavaScript.
JSON is a simple representation of data: the specification can be described in about one paragraph (the website proves it) and lists only six data types. This is a good thing in many ways:
- It’s easy to understand, parse, and remember.
- On the other hand, JSON’s expressive capabilities are limited because the only types are null, boolean, numeric, string, array, and object.
Although these types allow for an impressive amount of expressivity, there are a couple of additional types that are crucial for most applications, especially when working with a database e.g.
- JSON has no date type, which makes working with dates even more annoying than it usually is.
- There is a number type, but only one—there is no way to differentiate floats and integers, never mind any distinction between 32-bit and 64-bit numbers.
- There is no way to represent other commonly used types, either, such as regular expressions or functions.
MongoDB uses BSON as its data storage and transmission format to enhance performance and support complex data structures. BSON (Binary JSON) is a superset of JSON (JavaScript Object Notation) format to store documents and transfer data between the database and applications.
MongoDB adds support for a number of additional data types while keeping JSON’s essential key/value–pair nature.
Exactly how values of each type are represented varies by language, but this is a list of the commonly supported types and how they are represented as part of a document in the shell. The most common types are:
Null
The null type can be used to represent both a null value and a nonexistent field:
{"x" : null}
Boolean
There is a boolean type, which can be used for the values true
and false
:
{"x" : true}
Number
The shell defaults to using 64-bit floating-point numbers. Thus, these numbers both look “normal” in the shell:
{"x" : 3.14}
{"x" : 3} //still float
For integers, use the NumberInt
or NumberLong
classes, which represent 4-byte or 8-byte signed integers, respectively.
{"x" : NumberInt("3")} //32-bit or 4-byte
{"x" : NumberLong("3")} //64-bit or 8byte
String
Any string of UTF-8 characters can be represented using the string type:
{"x" : "foobar"}
Date
MongoDB stores dates as 64-bit integers representing milliseconds since the Unix epoch (January 1, 1970). The time zone is not stored:
{"x" : new Date()}
Regular expression
Queries can use regular expressions using JavaScript’s regular expression syntax:
{"x" : /foobar/i}
Array
Sets or lists of values can be represented as arrays:
{"x" : ["a", "b", "c"]}
Embedded document
Documents can contain entire documents embedded as values in a parent document:
{"x" : {"foo" : "bar"}}
Object ID
An object ID is a 12-byte ID for documents:
{"x" : ObjectId()}
Uncommon data types
There are also a few less common types that you may need, including:
Binary data
Binary data is a string of arbitrary bytes. It cannot be manipulated from the shell. Binary data is the only way to save non-UTF-8 strings to the database.
Code
MongoDB also makes it possible to store arbitrary JavaScript in queries and documents:
{"x" : function() { /* ... */ }}
Finally, there are a few types that are mostly used internally (or superseded by other types). These will be described in the text as needed.
We will see detailed descriptions of some commonly used data types in the next blog.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】