Mongodb для начинающих: знакомство и установка (часть 1/3)
Содержание:
- Behavior¶
- Replication¶
- Получение записи¶
- Specify Conditions Using Query Operators¶
- Почему не все так просто с MongoDB
- Queries¶
- Other Uses of the Document Structure¶
- Process Logging¶
- Install MongoDB Community Edition¶
- Почему вы никогда не должны использовать MongoDB
- Types¶
- Our Story
- Definition¶
- Графовая база данных Neo4j в PHP
- Additional Considerations¶
- Examples¶
- Опыт персонализации интернет-магазина на примере динамической рекомендации
- Database¶
- Considerations¶
- MongoDb for developers. Неделя 1
- Document Structure¶
- Как устроены сервисы управляемых баз данных в Яндекс.Облаке
- Run MongoDB Community Edition as a Windows Service¶
Behavior¶
updates all matching documents in
the collection that match the , using the criteria
to apply modifications.
Upsert
If and no documents match the ,
creates a new
document based on the and parameters.
If you specify on a sharded collection, you must
include the full shard key in the . For additional
behavior, see
.
See
.
Update with an Update Operator Expressions Document
For the modification specification, the
method can accept a document that
only contains expressions to
perform.
For example:
db.collection.updateMany( <query>, { $set { status "D" }, $inc { quantity 2 } }, ... )
Update with an Aggregation Pipeline
Starting in MongoDB 4.2, the method
can accept an aggregation pipeline that
specifies the modifications to perform. The pipeline can consist of
the following stages:
- and its alias
- and its alias
- and its alias .
Using the aggregation pipeline allows for a more expressive update
statement, such as expressing conditional updates based on current
field values or updating one field using the value of another field(s).
For example:
db.collection.updateMany( <query>, { $set { status "Modified", comments "$misc1", "$misc2" } }, { $unset "misc1", "misc2" } ... )
Note
The and used in the pipeline refers to the
aggregation stages and
respectively, and not the update operators and .
For examples, see .
Replication¶
Name | Description |
---|---|
Adds a member to a replica set. | |
Adds an to a replica set. | |
Returns the replica set configuration document. | |
Prevents the current member from seeking election as primary for a period of time. | |
Returns basic help text for functions. | |
Initializes a new replica set. | |
Prints a report of the status of the replica set from the perspective of the primary. | |
Prints a report of the status of the replica set from the perspective of the secondaries. | |
Re-configures a replica set by applying a new replica set configuration object. | |
Remove a member from a replica set. | |
Allows read operations on a secondary member. | |
Returns a document with information about the state of the replica set. | |
Causes the current to become a secondary which forces an . | |
Sets the member that this replica set member will sync from, overriding the default sync target selection logic. |
Получение записи¶
Для получения всех записей в коллекции используйте метод экземпляра коллекции.
Методу в качестве параметра можно передать объект, выполняющий роль фильтра для извлекаемых записей. Например, в следующем примере возвращаются все записи, у которых поле равно .
Чтобы получить только первую запись выборки, используйте метод .
Для получения n-первых записей имеется метод , принимающий количество возвращаемых записей.
Сортировка полученного результата осуществляется с помощью метода , который принимает объект, в котором ключ — сортирующее поле, а значение — порядок сортировки ( — по возрастанию, а — по убыванию).
Ограничение по выборке и сортировку можно задать в объекте, передаваемом вторым необязательным параметром.
С полным списком параметров можно ознакомиться в .
Specify Conditions Using Query Operators¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
-
Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
A can
use the to specify
conditions in the following form:
copy
{ <field1>: { <operator1>: <value1> }, ... }
A can
use the to specify
conditions in the following form:
copy
{ <field1>: { <operator1>: <value1> }, ... }
A can
use the to specify
conditions in the following form:
copy
{ <field1> { <operator1> <value1> }, ... }
In addition to the equality condition, MongoDB provides
various to specify
filter conditions. Use the
com.mongodb.client.model.Filters helper methods to
facilitate the creation of filter documents. For example:
copy
and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
A can
use the to specify
conditions in the following form:
copy
{ <field1>: { <operator1>: <value1> }, ... }
A can
use the to specify
conditions in the following form:
copy
<field1> => <operator1> => <value1> ], ...
A can
use the to specify
conditions in the following form:
copy
{ <field1> { <operator1> <value1> }, ... }
In addition to the equality condition, MongoDB provides
various to specify
filter conditions. Use the
com.mongodb.client.model.Filters helper methods to
facilitate the creation of filter documents. For example:
copy
and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
In addition to the equality filter, MongoDB provides
various to specify
filter conditions. Use the
FilterDefinitionBuilder
methods to create a filter document. For example:
copy
var builder = Builders<BsonDocument>.Filter; builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));
A can
use the to specify
conditions in the following form:
copy
{ <field1> => { <operator1> => <value1> }, ... }
A can
use the to specify
conditions in the following form:
copy
{ <field1> => { <operator1> => <value1> }, ... }
In addition to the equality condition, MongoDB provides
various to specify
filter conditions. Use the
helper methods to
facilitate the creation of filter documents. For example:
copy
and(gte(<field1>, <value1>), lt(<field2>, <value2>), equal(<field3>, <value3>))
The following example retrieves all documents from the
collection where equals either or :
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
-
Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
copy
db.inventory.find( { status { $in "A", "D" } } )
Copy the following filter into the Compass query bar and click
Find:
copy
{ status { $in "A", "D" } }
copy
cursor = db.inventory.find({"status" {"$in" "A", "D"]}})
copy
findIterable = collection.find(in("status", "A", "D"));
copy
const cursor = db.collection('inventory').find({ status { $in 'A', 'D' } });
copy
$cursor = $db->inventory->find(]]);
copy
cursor = db.inventory.find({"status" {"$in" "A", "D"]}})
copy
findPublisher = collection.find(in("status", "A", "D"));
copy
var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" }); var result = collection.Find(filter).ToList();
copy
$cursor = $db->coll("inventory")->find( { status => { '$in' => "A", "D" } } );
copy
client:inventoryfind(status { '$in' => 'A', 'D' })
copy
findObservable = collection.find(in("status", "A", "D"))
copy
cursor, err := coll.Find( context.Background(), bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}})
Note
Although you can express this query using the operator,
use the operator rather than the
operator when performing equality checks on the same field.
The operation corresponds to the following SQL statement:
copy
SELECT * FROM inventory WHERE status in ("A", "D")
Почему не все так просто с MongoDB
В последние несколько лет MongoDB приобрела огромную популярность среди разработчиков. То и дело в интернете появляются всякие статьи, как очередной молодой популярный проект выкинул на свалку истории привычные РСУБД, взял в качестве основной базы данных MongoDB, выстроил инфраструктуру вокруг неё, и как все после этого стало прекрасно. Даже появляются новые фреймворки и библиотеки, которые строят свою архитектуру целиком на Mongo (Meteor.js например).
По долгу работы я примерно 3 года занимаюсь разработкой и поддержкой нескольких проектов, которые используют MongoDB в качестве основной БД, и в этой статье хочу рассказать, почему на мой взгляд с MongoDB далеко не все так просто, как написано в мануалах, и к чему вы должны быть готовы, если вдруг решите взять MongoDB в качестве основной БД в ваш новый модный стартап 🙂
Все что описано ниже можно воспроизвести с использованием библиотеки PyMongo для работы с MongoDB из языка программирования Python. Однако скорее всего с аналогичными ситуациями вы можете столкнуться и при использовании других библиотек для других языков программирования.
Queries¶
In the shell, perform read operations using the
and
methods.
The method returns a cursor object
which the shell iterates to print documents on
screen. By default, prints the first 20. The
shell will prompt the user to “” to continue
iterating the next 20 results.
The following table provides some common read operations in the
shell:
Read Operations | Description |
---|---|
Find the documents matching the criteria in the The following example selects the documents in the copy coll = db.users; coll.find( { name "Joe" } ); For more information on specifying the criteria, see |
|
Find documents matching the criteria and return just The following example selects all documents from the collection copy coll = db.users; coll.find( { }, { name true } ); For more information on specifying the , see |
|
Return results in the specified . The following example selects all documents from the collection copy coll = db.users; coll.find().sort( { name 1 } ); |
|
Return the documents matching the criteria in the specified . |
|
Limit result to rows. Highly recommended if you need only a certain number of rows for best performance. |
|
Skip results. | |
Returns total number of documents in the collection. | |
Returns the total number of documents that match the query. The ignores and . For |
|
Find and return a single document. Returns null if not found. The following example selects a single document in the copy coll = db.users; coll.findOne( { name "Joe" } ); Internally, the |
Other Uses of the Document Structure¶
In addition to defining data records, MongoDB uses the document
structure throughout, including but not limited to: , , and
Query Filter Documents
Query filter documents specify the conditions that determine which
records to select for read, update, and delete operations.
You can use expressions to specify the equality
condition and query operator
expressions.
copy
{ <field1>: <value1>, <field2>: { <operator>: <value> }, ... }
For examples, see:
- Query Documents
- Query on Embedded/Nested Documents
- Query an Array
- Query an Array of Embedded Documents
Update Specification Documents
Update specification documents use to specify the data modifications to perform on
specific fields during an operation.
copy
{ <operator1>: { <field1>: <value1>, ... }, <operator2>: { <field2>: <value2>, ... }, ... }
For examples, see .
Process Logging¶
During normal operation, and
instances report a live account of all server activity and operations
to either
standard output or a log file. The following runtime settings
control these options.
-
. Limits the amount of information written to the
log or output. -
. Increases the amount of information written to
the log or output. You can also modify the logging verbosity during
runtime with the parameter or the
method in the shell. -
. Enables logging to a file, rather than the standard
output. You must specify the full path to the log file when adjusting
this setting. -
. Adds information to a log
file instead of overwriting the file.
Note
You can specify these configuration operations as the command line
arguments to mongod or mongos
For example:
copy
mongod -v --logpath /var/log/mongodb/server1.log --logappend
Starts a instance in mode, appending data to the log file at
.
The following also
affect logging:
-
. Displays recent messages from the
process log. -
. Rotates the log files for
processes only. See Rotate Log Files.
Install MongoDB Community Edition¶
Follow these steps to install MongoDB Community Edition using the
package manager.
1
Import the public key used by the package management system.
From a terminal, issue the following command to import the
MongoDB public GPG Key from https://www.mongodb.org/static/pgp/server-4.4.asc:
copy
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
The operation should respond with an .
However, if you receive an error indicating that is not
installed, you can:
-
Install and its required libraries using the following command:
copy
sudo apt-get install gnupg
-
Once installed, retry importing the key:
copy
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
2
Create a list file for MongoDB.
Create the list file
for your
version of Ubuntu.
Click on the appropriate tab for your version of Ubuntu.
If you are unsure of what Ubuntu version the host is running,
open a terminal or shell on the host and execute .
- Ubuntu 20.04 (Focal)
- Ubuntu 18.04 (Bionic)
- Ubuntu 16.04 (Xenial)
The following instruction is for Ubuntu 20.04 (Focal).
Create the
file for Ubuntu 20.04 (Focal):
copy
echo "deb https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
The following instruction is for Ubuntu 18.04
(Bionic).
Create the
file for Ubuntu 18.04 (Bionic):
copy
echo "deb https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
The following instruction is for Ubuntu 16.04
(Xenial).
Create the
file for Ubuntu 16.04 (Xenial):
copy
echo "deb https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
3
Issue the following command to reload the local package database:
copy
sudo apt-get update
4
Install the MongoDB packages.
You can install either the latest stable version of MongoDB or a
specific version of MongoDB.
- Install the latest version of MongoDB.
- Install a specific release of MongoDB.
To install the latest stable version, issue the following
copy
sudo apt-get install -y mongodb-org
To install a specific release, you must specify each component package
individually along with the version number, as in the
following example:
copy
sudo apt-get install -y mongodb-org=4.4.2 mongodb-org-server=4.4.2 mongodb-org-shell=4.4.2 mongodb-org-mongos=4.4.2 mongodb-org-tools=4.4.2
If you only install and do not include the
component packages, the latest version of each MongoDB package will be
installed regardless of what version you specified.
Optional. Although you can specify any available version of MongoDB,
will upgrade the packages when a newer version becomes
available. To prevent unintended upgrades, you can pin the package
at the currently installed version:
copy
echo "mongodb-org hold" | sudo dpkg --set-selections echo "mongodb-org-server hold" | sudo dpkg --set-selections echo "mongodb-org-shell hold" | sudo dpkg --set-selections echo "mongodb-org-mongos hold" | sudo dpkg --set-selections echo "mongodb-org-tools hold" | sudo dpkg --set-selections
Почему вы никогда не должны использовать MongoDB
Перевод
Дисклеймер от автора (автор — девушка): Я не разрабатываю движки баз данных. Я создаю веб-приложения. Я участвую в 4-6 разных проектах каждый год, то есть создаю много веб-приложений. Я вижу много приложений с различными требованиями и различными потребностями хранения данных. Я разворачивала большинство хранилищ, о которых вы слышали, и несколько, о которых даже не подозреваете.
Несколько раз я делала неправильный выбор СУБД. Эта история об одном таком выборе — почему мы сделали такой выбор, как бы узнали что выбор был неверен и как мы с этим боролись.Это все произошло на проекте с открытым исходным кодом, называемым Diaspora.
Types¶
Date
The shell provides various methods to return the date,
either as a string or as a object:
- method which returns the current date as a string.
-
constructor which returns a object using the
wrapper. -
constructor which returns a object using the
wrapper.
Internally, objects are stored as a signed
64-bit integer representing the number of milliseconds since the Unix
epoch (Jan 1, 1970).
Not all database operations and drivers support the full 64-bit range.
You may safely work with dates with years within the inclusive range
through .
Return Date as a String
To return the date as a string, use the method, as in the
following example:
copy
var myDateString = Date();
To print the value of the variable, type the variable name in the
shell, as in the following:
copy
myDateString
The result is the value of :
copy
Wed Dec 19 2012 010325 GMT-0500 (EST)
To verify the type, use the operator, as in the following:
copy
typeof myDateString
The operation returns .
Return
The shell wraps objects of type with the
helper; however, the objects remain of type .
The following example uses both the constructor and the
constructor to return objects.
copy
var myDate = new Date(); var myDateInitUsingISODateWrapper = ISODate();
You can use the operator with the constructor as
well.
To print the value of the variable, type the variable name in the
shell, as in the following:
copy
myDate
The result is the value of wrapped in the
helper:
copy
ISODate("2012-12-19T06:01:17.171Z")
To verify the type, use the operator, as in the
following:
copy
myDate instanceof Date myDateInitUsingISODateWrapper instanceof Date
The operation returns for both.
ObjectId
The shell provides the wrapper class
around the data type. To generate a new ObjectId, use
the following operation in the shell:
copy
new ObjectId
See
NumberLong
The shell treats all numbers as floating-point values
by default. The shell provides the
wrapper to handle 64-bit integers.
The wrapper accepts the long as a string:
copy
NumberLong("2090845886852")
The following examples use the wrapper to write to the
collection:
copy
db.collection.insertOne( { _id 10, calc NumberLong("2090845886852") } ) db.collection.updateOne( { _id 10 }, { $set { calc NumberLong("2555555000000") } } ) db.collection.updateOne( { _id 10 }, { $inc { calc NumberLong("5") } } )
Retrieve the document to verify:
copy
db.collection.findOne( { _id 10 } )
In the returned document, the field contains a
object:
copy
{ "_id" : 10, "calc" : NumberLong("2555555000005") }
If you use the to increment the value of a field that
contains a object by a float, the data type changes
to a floating point value, as in the following example:
-
Use to increment the field by , which the
shell treats as a float:copy
db.collection.updateOne( { _id 10 }, { $inc { calc 5 } } )
-
Retrieve the updated document:
copy
db.collection.findOne( { _id 10 } )
In the updated document, the field contains a floating
point value:copy
{ "_id" : 10, "calc" : 2555555000010 }
Note
Although the constructor accepts values
from the shell (i.e. without quotes), this is
not recommended. Specifying an integer value larger than JavaScript’s
defined (which is the number
) may lead to unexpected behavior.
The shell treats all numbers as floating-point values
by default. The shell provides the
constructor to explicitly specify 32-bit integers.
Our Story
MongoDB was founded in 2007 by Dwight Merriman, Eliot Horowitz and Kevin Ryan – the team behind DoubleClick.
At the Internet advertising company DoubleClick (now owned by Google), the team developed and used many custom data stores to work around the shortcomings of existing databases. The business served 400,000 ads per second, but often struggled with both scalability and agility. Frustrated, the team was inspired to create a database that tackled the challenges it faced at DoubleClick.
MongoDB is the leading modern, general purpose database platform, designed to unleash the power of software and data for developers and the applications they build. Headquartered in New York, with offices across North America, Europe, and Asia-Pacific, we are close to where you do business. MongoDB has more than 22,200 customers in more than 100 countries. The MongoDB database platform has been downloaded over 125 million times and there have been more than 1 million MongoDB University registrations.
125+ milliondownloads
Definition¶
-
selects documents where the value of the
is an instance of the specified type(s).
Querying by data type is useful when dealing with highly
unstructured data where data types are not predictable.A expression for a single type has
the following syntax:Changed in version 3.2.
copy
{ field { $type <BSON type> } }
You can specify either the number or alias for the
The expression can also accept an array of
types and has the following syntax:copy
{ field { $type <BSON type1> , <BSON type2>, ... } }
The above query will match documents where the value is
any of the listed types. The types specified in the array can be
either numeric or string aliases.See for an example.
describes the BSON types and
their corresponding numeric and string aliases.
Графовая база данных Neo4j в PHP
Из песочницы
В последнее время я все чаще слышу о NoSQL и о графовых базах данных в частности. Но воспользовавшись хабропоиском с удивлением обнаружил, что статей на эту тему не так и много, а по запросу «Neo4j», так вообще 4 результата, где косвенно упоминается это название в тексте статей.
Что такое Neo4j?
Neo4j — это высокопроизводительная, NoSQL база данных основанная на принципе графов. В ней нет такого понятия как таблицы со строго заданными полями, она оперирует гибкой структурой в виде нод и связей между ними.
Как я докатился до этого?
Уже более года я не использовал в своих проектах SQL, с того времени, как попробовал документо-ориентированную СУБД «MongoDB». После MySQL моей радости не было предела, как все просто и удобно можно делать в MongoDB. За год, в нашей студии создания сайтов, переписали тройку CMS, использующих основные фишки Mongo c её документами, и с десяток сайтов работающих на их основе. Всё было хорошо, и я уже начал забывать, что такое писать запросы в полсотни строк на каждое действие с БД и все бы ничего пока на мою голову не свалился проект с кучей отношений, которые ну никак не укладывались в документы. Возвращаться к SQL очень не хотелось, и пару дней я потратил чисто на поиск NoSQL решения, позволяющего делать гибкие связи — на графовые СУБД. И по ряду причин мой выбор остановился на Neo4j, одна из главных причин — это то, что мой движок был написан на PHP, а для неё был написан хороший драйвер «Neo4jPHP», который охватывает почти 100% REST-интерфейса, предоставляющегося сервером Noe4j.
Additional Considerations¶
Localhost Binding by Default
By default, MongoDB launches with set to
, which binds to the localhost network interface. This
means that the can only accept connections from
clients that are running on the same machine. Remote clients will not be
able to connect to the , and the will
not be able to initialize a unless this value is set
to a valid network interface.
This value can be configured either:
- in the MongoDB configuration file with , or
- via the command-line argument
Warning
Before binding to a non-localhost (e.g. publicly accessible)
IP address, ensure you have secured your cluster from unauthorized
access. For a complete list of security recommendations, see
Security Checklist. At minimum, consider
and
hardening network infrastructure.
For more information on configuring , see
IP Binding.
Point Releases and
If you installed MongoDB with the Windows installer (), the
automatically upgrades within its (e.g. 4.2.1 to 4.2.2).
Upgrading a full release series (e.g. 4.0 to 4.2) requires a new
installation.
Add MongoDB binaries to the System PATH
All command-line examples in this tutorial are provided as absolute paths to the MongoDB binaries. You can add to your System and then omit the full path to the MongoDB binaries.
Examples¶
Querying by Data Type
The contains addresses and zipcodes, where
has , , , and
values:
copy
db.addressBook.insertMany( { "_id" 1, address "2030 Martian Way", zipCode "90698345" }, { "_id" 2, address "156 Lunar Place", zipCode 43339374 }, { "_id" 3, address "2324 Pluto Place", zipCode NumberLong(3921412) }, { "_id" 4, address "55 Saturn Ring" , zipCode NumberInt(88602117) }, { "_id" 5, address "104 Venus Drive", zipCode "834847278", "1893289032"]} )
The following queries return all documents where is the
type or is an array containing an element of
the specified type:
copy
db.addressBook.find( { "zipCode" { $type 2 } } ); db.addressBook.find( { "zipCode" { $type "string" } } );
These queries return:
copy
{ "_id" 1, "address" "2030 Martian Way", "zipCode" "90698345" } { "_id" 5, "address" "104 Venus Drive", "zipCode" "834847278", "1893289032" }
The following queries return all documents where is the
type or is an array containing an element of
the specified type:
copy
db.addressBook.find( { "zipCode" { $type 1 } } ) db.addressBook.find( { "zipCode" { $type "double" } } )
These queries return:
copy
{ "_id" 2, "address" "156 Lunar Place", "zipCode" 43339374 }
The following query uses the alias to return documents where
is the type , , or
or is an array containing an element of the specified types:
copy
db.addressBook.find( { "zipCode" { $type "number" } } )
These queries return:
copy
{ "_id" 2, "address" "156 Lunar Place", "zipCode" 43339374 } { "_id" 3, "address" "2324 Pluto Place", "zipCode" NumberLong(3921412) } { "_id" 4, "address" "55 Saturn Ring", "zipCode" 88602117 }
Querying by Multiple Data Type
The collection contains names and averages, where
has , , and values:
copy
db.grades.insertMany( { "_id" 1, name "Alice King" , classAverage 87.333333333333333 }, { "_id" 2, name "Bob Jenkins", classAverage "83.52" }, { "_id" 3, name "Cathy Hart", classAverage "94.06" }, { "_id" 4, name "Drew Williams" , classAverage NumberInt("93") } )
The following queries return all documents where is the
type or or is an array containing
an element of the specified types. The first query uses numeric aliases
while the second query uses string aliases.
copy
db.grades.find( { "classAverage" { $type 2 , 1 } } ); db.grades.find( { "classAverage" { $type "string" , "double" } } );
These queries return the following documents:
copy
{ "_id" 1, "name" "Alice King", "classAverage" 87.33333333333333 } { "_id" 2, "name" "Bob Jenkins", "classAverage" "83.52" } { "_id" 3, "name" "Cathy Hart", "classAverage" "94.06" }
Опыт персонализации интернет-магазина на примере динамической рекомендации
Привет, Хабр!
Поделюсь опытом о том, как собрали собственную систему персонализации на базе «знаний» о потенциальном покупателе.
Единственное чем отличалось наше решение от классических — это использование комбинированной связки ряда решений и удовлетворял списку требований:
- сервис должен был работать сразу на N сайтах
- динамическая сегментация аудитории
- Коллаборативная фильтрация для целей прогнозирования в разных состояниях сегментов аудитории
- предварительно сгенеренная статика в виде рекомендованного контента + динамический подмес товаров на основе анализа кликстрима
- изменение контента, практически в реал-тайме, из оперативной памяти, с учетом динамических коэффициентов
Об этом подробнее 🙂 И о тех граблях, которые помогали нам меняться стек в лучшую сторону.
Database¶
Name | Description |
---|---|
Runs a command against the database. | |
Runs admin/diagnostic pipeline which does not require an underlying collection. | |
Deprecated. Copies a database from a remote host to the current host when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later. | |
Returns help information for a . | |
Deprecated. Copies a database to another database on the current host when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later. | |
Creates a new collection or a view. Commonly used to create a capped collection. | |
Creates a view. | |
Reports the current in-progress operations. | |
Removes the current database. | |
Deprecated. Passes a JavaScript function for server-side JavaScript evaluation when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later. | |
Flushes writes to disk and locks the database to prevent write operations and assist backup operations. Wraps . | |
Allows writes to continue on a database locked with . | |
Returns a collection or view object. Used to access collections with names that are not valid in the shell. | |
Returns collection information for all collections and views in the current database. | |
Lists all collections and views in the current database. | |
Checks and returns the status of the last operation. Wraps . | |
Returns the status document for the last operation. Wraps . | |
Returns the log message verbosity levels. | |
Returns the connection object for the current connection. | |
Returns the name of the current database. | |
Returns the current profiling level for database operations. | |
Returns a document that reflects the current profiling level and the profiling threshold. | |
Returns a document with replication statistics. | |
Provides access to the specified database. | |
Displays descriptions of common object methods. | |
Returns a document with information about the system MongoDB runs on. Wraps | |
Returns a document that reports the state of the replica set. | |
Terminates a specified operation. | |
Displays a list of common database commands. | |
Ends an authenticated session. | |
Prints statistics from every collection. Wraps . | |
Prints a report of the status of the replica set from the perspective of the primary. | |
Prints a report of the sharding configuration and the chunk ranges. | |
Prints a report of the status of the replica set from the perspective of the secondaries. | |
Deprecated. Resets the last error status. | |
Runs a database command. | |
Returns a document that displays the compilation parameters for the instance. Wraps . | |
Returns a document with information about the runtime used to start the MongoDB instance. Wraps . | |
Returns a document that provides an overview of the state of the database process. | |
Sets a single log message verbosity level. | |
Modifies the current level of database profiling. | |
Shuts down the current or process cleanly and safely. | |
Returns a document that reports on the state of the current database. | |
Returns the version of the instance. | |
Opens a for a database to report on all its non- collections. Cannot be opened on the , or databases. |
Considerations¶
Platform Support
MongoDB 4.4 Community Edition supports the following
64-bit Ubuntu LTS (long-term support) releases on
architecture:
- 20.04 LTS (“Focal”)
- 18.04 LTS (“Bionic”)
- 16.04 LTS (“Xenial”)
MongoDB only supports the 64-bit versions of these platforms.
MongoDB 4.4 Community Edition on Ubuntu also supports the
and
architectures on
select platforms.
See for more information.
Windows Subsystem for Linux (WSL) — Unsupported
MongoDB does not support the Windows Subsystem for Linux (WSL).
Production Notes
Before deploying MongoDB in a production environment, consider the
Production Notes document which offers
performance considerations and configuration recommendations for
production MongoDB deployments.
MongoDb for developers. Неделя 1
Вечер добрый, хабр. На прошлой неделе стартовал курс «MongoDb for developers» от 10gen, о котором уже писали на хабре. Если вы смотрели уроки, то можете смело проходить мимо. Остальным — добро пожаловать.
В этой статье будет изложен основной материал первой недели обучения. Если аудитория проявит интерес — то подобные посты будут выходить в конце каждой недели.
Мы вкратце рассмотрим, что представляет собой MongoDB, сравним разницу в структурах данных между монго и реляционными базами для простого веб-приложения, поиграемся с шеллом, и немножко покодим на пхп и питоне.Зачем эта статья? Предвижу подобный вопрос. Не все успели записаться на курсы, не у всех есть достаточно свободного времени, не у всех хорошо обстоят дела с восприятием устной английской речи. Ну и для гуглящих подобный материал не помешает.
Document Structure¶
MongoDB documents are composed of field-and-value pairs and have the
following structure:
copy
{ field1 value1, field2 value2, field3 value3, ... fieldN valueN }
The value of a field can be any of the BSON data types, including other documents, arrays, and arrays
of documents. For example, the following document contains values of varying types:
copy
var mydoc = { _id ObjectId("5099803df3f4948bd2f98391"), name { first "Alan", last "Turing" }, birth new Date('Jun 23, 1912'), death new Date('Jun 07, 1954'), contribs "Turing machine", "Turing test", "Turingery" ], views NumberLong(1250000) }
The above fields have the following data types:
- holds an .
-
holds an embedded document that contains the fields
and . - and hold values of the Date type.
- holds an array of strings.
- holds a value of the NumberLong type.
Field Names
Field names are strings.
have the following restrictions on field
names:
The field name _id is reserved for use as a primary key; its
value must be unique in the collection, is immutable, and may be of
any type other than an array.
-
Field names cannot contain the character.
-
Top-level field names cannot start with the dollar sign () character.
Otherwise, starting in MongoDB 3.6, the server permits storage of
field names that contain dots (i.e. ) and dollar signs (i.e.
).Important
The MongoDB Query Language cannot always meaningfully express
queries over documents whose field names contain these characters
(see SERVER-30575).Until support is added in the query language, the use of and
in field names is not recommended and is not supported by
the official MongoDB drivers.
BSON documents may have more than one field with the same name.
Most MongoDB interfaces, however, represent MongoDB
with a structure (e.g. a hash table) that does not support duplicate
field names. If you need to manipulate documents that have more than one
field with the same name, see the driver documentation for your driver.
Some documents created by internal MongoDB processes may have duplicate
fields, but no MongoDB process will ever add duplicate fields to an
existing user document.
Как устроены сервисы управляемых баз данных в Яндекс.Облаке
Когда ты доверяешь кому-то самое дорогое, что у тебя есть, – данные своего приложения или сервиса – хочется представлять, как этот кто-то будет обращаться с твоей самой большой ценностью.
Меня зовут Владимир Бородин, я руководитель платформы данных Яндекс.Облака. Сегодня я хочу рассказать вам, как всё устроено и работает внутри сервисов Yandex Managed Databases, почему всё сделано именно так и в чём преимущества – с точки зрения пользователей – тех или иных наших решений. И конечно, вы обязательно узнаете, что мы планируем доработать в ближайшее время, чтобы сервис стал лучше и удобнее для всех, кому он нужен.
Что ж, поехали!
Run MongoDB Community Edition as a Windows Service¶
Starting in version 4.0, you can install and configure MongoDB as a
Windows Service during the install, and the MongoDB service
is started upon successful installation. MongoDB is configured using
the configuration file .
Start MongoDB Community Edition as a Windows Service
To start/restart the MongoDB service, use the Services console:
- From the Services console, locate the MongoDB service.
- Right-click on the MongoDB service and click Start.
To begin using MongoDB, connect a shell
to the running MongoDB instance. To connect, open a Command
Interpreter with Administrative privileges and run:
copy
"C:\Program Files\MongoDB\Server\4.4\bin\mongo.exe"
For more information on connecting a
shell, such as to connect to a MongoDB instance running on a different
host and/or port, see The mongo Shell. For information on CRUD
(Create,Read,Update,Delete) operations, see:
- Insert Documents
- Query Documents
- Update Documents
- Delete Documents
Stop MongoDB Community Edition as a Windows Service
To stop/pause the MongoDB service, use the Services console:
- From the Services console, locate the MongoDB service.
- Right-click on the MongoDB service and click Stop (or Pause).