和我一起学习 MongoDB - 第二部分





5.00/5 (3投票s)
这是探索 MongoDB shell 的延续,我们将执行一些 MongoDB shell 命令。
引言
这是“跟我一起学习 MongoDB”系列的第二篇文章。如果您还没有阅读我之前关于此主题的帖子,我强烈建议您在这里查看。这是探索 MongoDB shell 的延续,我们将执行一些 MongoDB shell 命令。为了方便参考,我将尝试为我执行的每个步骤添加截图。我希望这能帮助您跟我一起学习。感谢您的阅读。
背景
就像我说的,这将是该系列的第二部分。我相信您已经对 MongoDB 以及如何设置它有了足够的了解?如何使用 MongoDB shell?如果您无法自己回答这些问题,请考虑再次阅读我的上一篇文章。
MongoDB Shell,完美的命令行界面
为了说明这一点,我们可以在 MongoDB shell 中执行任何操作。我将执行一些 CRUD 操作(创建、读取、更新、删除)在 MongoDB shell 中。为此,我们可以使用 MongoDB 导入命令。即使数据是.tsv、.csv、.json等格式,MongoDB 导入命令也可以为您完成这项工作。让我们看看它们是如何工作的。
第一步,让我们查看一些文档。
C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --help
以上命令将为您提供所有可用的选项以开始使用。
Usage:
mongoimport <options> <file>
Import CSV, TSV or JSON data into MongoDB. If no file is provided, mongoimport reads from stdin.
See http://docs.mongodb.org/manual/reference/program/mongoimport/ for more information.
general options:
/help print usage
/version print the tool version and
exit
verbosity options:
/v, /verbose:<level> more detailed log output
(include multiple times for
more verbosity, e.g. -vvvvv,
or specify a numeric value,
e.g. --verbose=N)
/quiet hide all log output
connection options:
/h, /host:<hostname> mongodb host to connect to
(setname/host1,host2 for
replica sets)
/port:<port> server port (can also use
--host hostname:port)
kerberos options:
/gssapiServiceName:<service-name> service name to use when
authenticating using
GSSAPI/Kerberos ('mongodb' by
default)
/gssapiHostName:<host-name> hostname to use when
authenticating using
GSSAPI/Kerberos (remote
server's address by default)
ssl options:
/ssl connect to a mongod or mongos
that has ssl enabled
/sslCAFile:<filename> the .pem file containing the
root certificate chain from
the certificate authority
/sslPEMKeyFile:<filename> the .pem file containing the
certificate and key
/sslPEMKeyPassword:<password> the password to decrypt the
sslPEMKeyFile, if necessary
/sslCRLFile:<filename> the .pem file containing the
certificate revocation list
/sslAllowInvalidCertificates bypass the validation for
server certificates
/sslAllowInvalidHostnames bypass the validation for
server name
/sslFIPSMode use FIPS mode of the
installed openssl library
authentication options:
/u, /username:<username> username for authentication
/p, /password:<password> password for authentication
/authenticationDatabase:<database-name> database that holds the
user's credentials
/authenticationMechanism:<mechanism> authentication mechanism to
use
namespace options:
/d, /db:<database-name> database to use
/c, /collection:<collection-name> collection to use
uri options:
/uri:mongodb-uri mongodb uri connection string
input options:
/f, /fields:<field>[,<field>]* comma separated list of
fields, e.g. -f name,age
/fieldFile:<filename> file with field names - 1 per
line
/file:<filename> file to import from; if not
specified, stdin is used
/headerline use first line in input
source as the field list (CSV
and TSV only)
/jsonArray treat input source as a JSON
array
/parseGrace:<grace> controls behavior when type
coercion fails - one of:
autoCast, skipField, skipRow,
stop (defaults to 'stop')
(default: stop)
/type:<type> input format to import: json,
csv, or tsv (defaults to
'json') (default: json)
/columnsHaveTypes indicated that the field list
(from --fields, --fieldsFile,
or --headerline) specifies
types; They must be in the
form of
'<colName>.<type>(<arg>)'.
The type can be one of: auto,
binary, bool, date, date_go,
date_ms, date_oracle, double,
int32, int64, string. For
each of the date types, the
argument is a datetime layout
string. For the binary type,
the argument can be one of:
base32, base64, hex. All
other types take an empty
argument. Only valid for CSV
and TSV imports. e.g.
zipcode.string(),
thumbnail.binary(base64)
ingest options:
/drop drop collection before
inserting documents
/ignoreBlanks ignore fields with empty
values in CSV and TSV
/maintainInsertionOrder insert documents in the order
of their appearance in the
input source
/j, /numInsertionWorkers:<number> number of insert operations
to run concurrently (defaults
to 1) (default: 1)
/stopOnError stop importing at first
insert/upsert error
/mode:[insert|upsert|merge] insert: insert only. upsert:
insert or replace existing
documents. merge: insert or
modify existing documents.
defaults to insert
/upsertFields:<field>[,<field>]* comma-separated fields for
the query part when --mode is
set to upsert or merge
/writeConcern:<write-concern-specifier> write concern options e.g.
--writeConcern majority,
--writeConcern '{w: 3,
wtimeout: 500, fsync: true,
j: true}'
/bypassDocumentValidation bypass document validation
使用 MongoDB Shell 将数据插入 MongoDB
现在假设我有以下 JSON 数据,我们将把它插入到我们的数据库集合中。
[
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,0,0,1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0,0,255,1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,0,1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "#0F0"
}
}
]
为此,我们需要使用以下命令
C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --db mylearning
--collection colors --jsonArray --file colors.json
在这里,您可以看到,我们提供了数据库名称、集合名称、文件的数据类型以及文件名。
如果您遇到“`Failed: open colors.json: The system cannot find the file specified.`”错误,请确保该文档位于服务器文件夹中,在我的情况下是“`C:\Program Files\MongoDB\Server\3.4\bin`”。如果一切正常,您将能够看到如下所示的输出
C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --db mylearning --collection colors
--jsonArray --file colors.json
2018-03-01T16:35:35.470+0530 connected to: localhost
2018-03-01T16:35:36.012+0530 imported 6 documents
C:\Program Files\MongoDB\Server\3.4\bin>
从 MongoDB 集合中读取数据
现在我们有了 colors 集合,让我们检查一下数据库是否包含我们期望的数据。
C:\Program Files\MongoDB\Server\3.4\bin>mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2018-03-01T16:24:43.793+0530 I CONTROL [initandlisten]
2018-03-01T16:24:43.793+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled
for the database.
2018-03-01T16:24:43.793+0530 I CONTROL [initandlisten] ** Read and write access to data
and configuration is unrestricted.
2018-03-01T16:24:43.793+0530 I CONTROL [initandlisten]
MongoDB Enterprise > use mylearning
switched to db mylearning
MongoDB Enterprise > show collections
chats
colors
messages
MongoDB Enterprise > db.colors.count
function (query, options) {
query = this.find(query);
// Apply options and return the result of the find
return QueryHelpers._applyCountOptions(query, options).count(true);
}
MongoDB Enterprise > db.colors.count()
6
MongoDB Enterprise >
当您使用count
时,请确保将其视为一个函数count()
。我们有count
为6
,这就是我们期望的。对吗?您不认为我们应该从该集合中提取一些数据吗?是的,使用一些过滤器?
MongoDB Enterprise > db.colors.find({"type": "primary"})
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19d"), "color" : "black",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19e"), "color" : "yellow",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a1"), "color" : "red",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 0, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a2"), "color" : "blue",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
MongoDB Enterprise >
我们已成功导入数据,并已获取类型为 primary 的颜色。我认为应该有一种自定义颜色,其类型为 primary。我们现在可以这样做吗?
MongoDB Enterprise > db.colors.insert({
... "color": "custome",
... "category": "hue",
... "type": "primary",
... "code": {
... "rgba": [255,1,255,1],
... "hex": "#FF1"
... }
... }
... )
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise >
现在,如果您运行我们之前的查询,您将看到如下所示的输出
MongoDB Enterprise > db.colors.find({"type": "primary"})
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19d"), "color" : "black",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19e"), "color" : "yellow",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a1"), "color" : "red",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 0, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a2"), "color" : "blue",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custome",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, 1 ], "hex" : "#FF1" } }
MongoDB Enterprise >
更新 MongoDB 中的文档
哇,我们现在有了数据。我们对我们的数据库执行了创建
和读取
操作。现在是时候更新文档了。让我们继续为我们创建的颜色添加一个新属性“`manuallyCreated`”。这将帮助我们轻松找到此类条目。
MongoDB Enterprise > db.colors.update({
... "color":"custome"
... }
... ,{
... $set:{"manuallyCreated":"True"}}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise >
现在让我们查找所有手动创建的颜色,是的,我们知道将只有一条记录。
MongoDB Enterprise > db.colors.find({"manuallyCreated":"True"})
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custome",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, 1 ], "hex" : "#FF1" },
"manuallyCreated" : "True" }
MongoDB Enterprise >
让我们将颜色名称从“`custome`”更新为“`custom`”,抱歉打错了字。
MongoDB Enterprise > db.colors.update({"_id" : ObjectId("5a97e3202c19f0e958477e06")},
... {$set:{"color":"custom"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise >
啊,我犯了一个错误。我错误地运行了以下查询
MongoDB Enterprise > db.colors.update({ "color":"custom" } ,{ $set:{"code.rgba" : [ 255, 1, 255]}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
您知道该查询刚刚做了什么吗?它只是将我们自定义颜色的 rgba 更新为三点数组“`[255, 1, 255]`”。这不是我想要的。现在我们能做什么?我们需要向该集合添加一个值。让我们现在就去做。
MongoDB Enterprise > db.colors.update({ "color":"custom" } ,{ $addToSet:{"code.rgba" : "1" }} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise > db.colors.find({"manuallyCreated":"True"})
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custom",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, "1" ],
"hex" : "#FF1" }, "manuallyCreated" : "True" }
MongoDB Enterprise >
请注意,还有一个更新,它只会更新整个文档。在这种情况下,如果您没有为每个属性提供值,它将覆盖相同的值。让我们来看一个例子。
MongoDB Enterprise > db.colors.update({"color":"red"},{"color":"test"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise > db.colors.find({})
在这里,我们只发出一个命令将颜色 red 更新为颜色 test,因为我们没有在查询中提供其他属性作为查询的一部分,运行查询后,将只有一个属性,即color
。
MongoDB Enterprise > db.colors.find({})
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f1"), "color" : "black",
"category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f2"), "color" : "test" }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f3"),
"color" : "white", "category" : "value", "code" : { "rgba" : [ 0, 0, 0, 1 ], "hex" : "#FFF" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f4"),
"color" : "blue", "category" : "hue", "type" : "primary", "code" :
{ "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f5"),
"color" : "yellow", "category" : "hue", "type" : "primary", "code" :
{ "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f6"),
"color" : "green", "category" : "hue", "type" : "secondary", "code" :
{ "rgba" : [ 0, 255, 0, 1 ], "hex" : "#0F0" } }
MongoDB Enterprise > db.colors.find({"color":"test"})
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f2"), "color" : "test" }
MongoDB Enterprise >
删除 MongoDB Shell 中的文档
因此,我们添加了一种自定义颜色,后来我们发现它在我们的文档中不再需要,因为我们找到了与另一种颜色完全匹配的颜色。现在我们需要删除我们添加的那个。
MongoDB Enterprise > db.colors.remove({"color":"custom"})
WriteResult({ "nRemoved" : 1 })
MongoDB Enterprise >
让我们再次检查它是否真的被删除了。
MongoDB Enterprise > db.colors.find({"color":"custom"})
MongoDB Enterprise >
find 查询没有返回任何记录。
删除整个集合
我们对集合执行了 CRUD 操作,如果我们需要删除整个集合怎么办?
MongoDB Enterprise > db.colors.drop()
true
MongoDB Enterprise >
就这样,我们完成了这篇博文。我很快就会发布本系列的续集。在此之前,再见。
结论
非常感谢阅读。我是否遗漏了你认为需要的内容?你觉得这篇帖子有用吗?希望你喜欢这篇文章。请分享你宝贵的建议和反馈。
现在轮到你了。你有什么想法?
如果您有任何与本帖无关的问题,最好在 C# Corner、Code Project、Stack Overflow、ASP.NET 论坛上发布,而不是在这里发表评论。在 Twitter 上或通过电子邮件向我发送您在那里提出的问题的链接,如果我能做到,我一定会尽力提供帮助。