02 mongodb学习笔记 - xiaoxin01/Blog GitHub Wiki

简介

文档数据库,每条document包含多个键值对,值除了是字符串以外,还可以是其他document。

好处:

  1. 可以减少昂贵的join操作,使用array代替
  2. 动态的栏位,方便扩展和多态

关键功能:

  • High Performance
    • Support for embedded data models reduces I/O activity on database system.
    • Indexes support faster queries and can include keys from embedded documents and arrays.
  • Rich Query Language
  • High Availability
    • automatic failover
    • data redundancy.
  • Horizontal Scalability
    • Sharding distributes data across a cluster of machines.
    • Starting in 3.4, MongoDB supports creating zones of data based on the shard key.
  • Support for Multiple Storage Engines
    • WiredTiger Storage Engine (including support for Encryption at Rest)
    • In-Memory Storage Engine.

入门

mongodb的database和collection都是在插入document的时候自动创建,所以无需特别的指令

  • db:输出当前所在db名称
  • use [db]:切换到db
  • insert([json-object|json-array])/insertOne([json-object])/insertMany([json-array]):插入document,如果不包含_id栏位,则会自动创建
  • db.collection.find({})[.pretty()]:查找所有document
  • db.collection.find([json-object]):查找指定document
    • db.collection.find( { size: { h: 14, w: 21, uom: "cm" } } )
    • db.collection.find( { tags: [ "red", "blank" ] } )
  • db.inventory.find( {}, [projection-json-object] ):返回指定栏位,默认返回所有栏位
    • db.inventory.find( {}, { _id: 0, item: 1, status: 1 } )

The maximum BSON document size is 16 megabytes.

CRUD

insert

  • db.collection.insertOne()
  • db.collection.insertMany()
  • db.collection.insert()

下面的方法也可以插入数据:

  • db.collection.update() when used with the upsert: true option.
  • db.collection.updateOne() when used with the upsert: true option.
  • db.collection.updateMany() when used with the upsert: true option.
  • db.collection.findAndModify() when used with the upsert: true option.
  • db.collection.findOneAndUpdate() when used with the upsert: true option.
  • db.collection.findOneAndReplace() when used with the upsert: true option.
  • db.collection.save().
  • db.collection.bulkWrite().

query

db.collection.find(query, projection)
{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }
{ "_id": "oranges", "qty": { "in stock": 8, "ordered": 12 } }
{ "_id": "avocados", "qty": "fourteen" }

查询内嵌文档时,必须加引号:"hobby.movies":"hero"

Comparison

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$in Matches any of the values specified in an array.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$nin Matches none of the values specified in an array.

Logical

Name Description
$and Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

更多查询操作符

sort

Value Description
1 升序
-1 降序

只返回指定字段

p

update

  • db.collection.update(, , ):默认只改1个,可以通过multi: true options来修改多个
  • db.collection.updateOne(, , ):默认只改1个
  • db.collection.updateMany(, , )
  • db.collection.replaceOne(, , ):只修改某些属性

Update Operators

Fields

Name Description
$currentDate Sets the value of a field to current date, either as a Date or a Timestamp.
$inc 自增,set money = money + 100 -> $inc: {money: 100}
$min Only updates the field if the specified value is less than the existing field value.
$max Only updates the field if the specified value is greater than the existing field value.
$mul Multiplies the value of the field by the specified amount.
$rename Renames a field.
$set Sets the value of a field in a document.
$setOnInsert Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
$unset Removes the specified field from a document.

$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

operator

delete

  • db.collection.deleteOne()
  • db.collection.deleteMany()
  • db.collection.remove()

下面的方法也可以删除:

  • db.collection.findOneAndDelete()
  • db.collection.findAndModify()
  • db.collection.findAndModify()
  • db.collection.bulkWrite()

drop():删除collection dropDatabase():删除database

code

可以用类似js的语法来写代码段

var arr = [];
for(var i=0; i<1000; i++) {
    arr.push({num: i});
}
db.collection.insert(arr)

Data Model

Reference

  • 一对一
  • 一对多/多对一
  • 多对多

两种方式:

  1. Embedded Data, 内嵌文档

一般来说,下述情况建议使用内嵌数据:

  • 数据对象之间有 “contains” (包含) 关系。 参见 一对一关系建模:内嵌文档模型。
  • 数据对象之间有一对多的关系。 这些情况下 “多个”或者子文档会经常和父文档一起被显示和查看。请参见 一对多关系建模: 内嵌文档模型。
    • 比如 address 信息会经常和 name 字段一起被查询出来并显示, 那么应用程序必须发出额外的请求去解析并读取父文档。在这里更好的选择是把 address 数据直接内嵌到 patron 文档里面
  1. reference

一般来说,在下述情况下可以使用规范化模型:

  • 当内嵌数据会导致很多数据的重复,并且读性能的优势又不足于盖过数据重复的弊端时候。
  • 需要表达比较复杂的多对多关系的时候。
  • 大型多层次结构数据集。

数据建模

树形结构(可用于获取父子,祖先关系,取决于业务逻辑):

data-models-tree-structures

副本

分片

更多参考:data-model-operations

导入数据:

mongoimport -d [database] -c [collection] --file [datafile] -u [username] -p [password] -h localhost:27017 --authenticationDatabase admin

查询:

db.collection.find(query, projection)
db.getCollection([collection]).find({field:{$regex:"[text]"}})

返回指定的field:

{"id":1, "description":1}

连接字符串:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]

https://docs.mongodb.com/manual/reference/connection-string/

.net core使用mongodb

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-3.1&tabs=visual-studio

参考:

mongodb manual

⚠️ **GitHub.com Fallback** ⚠️