MongoDB-Usage

1. Use of MongDB

-- 显示数据库
show dbs
-- 切换/创建数据库
use dbname
-- 删除数据库

MongoDB users and permissions

List of user permissions

Read Allow the user to read the specified database
readWrite Allow the user to read and write the specified database
dbAdmin Allows users to perform administrative functions in the specified database, such as index creation, deletion, viewing statistics or accessing system.profile
userAdmin Allow users to write to the system.users collection, you can create, delete and manage users in the specified database
clusterAdmin Only available in the admin database, granting the user administrative privileges for all shard and replica set related functions
readAnyDatabase Only available in the admin database, granting the user read access to all databases
readWriteAnyDatabase Only available in the admin database, giving users read and write permissions for all databases
userAdminAnyDatabase Only available in the admin database, giving the user userAdmin permissions for all databases
dbAdminAnyDatabase Only available in the admin database, giving the user dbAdmin privileges for all databases
root Only available in the admin database. super account, super authority

User additions, deletions, checks and modifications

①, create a user (createUser)

mongodb has a user management mechanism, simply described as, there is a management user group, and the users in this group are specially set up for managing ordinary users, and they are called administrators for the time being. Administrators usually do not have read and write permissions to the database, but only the authority to operate users, so we only need to grant the administrator the userAdminAnyDatabase role. In addition, the administrator account must be created under the admin database.

  • Switch to the Admin repository
use admin
  • View users in admin
db.system.users.find()
  • create user
  • In MongoDB, you can use the db.createUser({user information}) function to create a user.
    • 1) user: create a new user name.
    • 2) pwd: create a new user password.
    • 3) customData: store some user-related custom data, this attribute can also be ignored.
    • 4) roles: array type, configure user permissions.
db.createUser({ 
 user: "<name>",
 pwd: "<cleartext password>",
 customData: { <any information> },
 roles: [
 { role: "<role>", db: "<database>" } | "<role>",
 ...
 ]
});
db.createUser({
   
   user:"itxiong",pwd:"itxiong",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
  • reboot
db.shutdownServer()

②. Update users

  • Role:
    • db.updateUser("user name", {"roles":[{"role":"role name"},{"update item 2":"update content"}]})
  • password:
    • db.updateUser("username", {"pwd":"new password"})

If there is no prompt, it means the update is successful. Exit the current client and reconnect to take effect

  • update role
db.updateUser("itxiong", {
   
   "roles":[{
   
   "role":"userAdminAnyDatabase","db":"admin"},{
   
   "role":"dbAdminAnyDatabase","db":"admin"}]})
  • update password
  • There are two ways to update user passwords:
    • 1) Use the db.updateUser() function to update the password.
    • 2) Use the db.changeUserPassword() function to update the password
      • db.changeUserPassword("username", "new password")
  1. method one
db.changeUserPassword("itxiong","itxiong")
  1. way two
db.updateUser("itxiong",{
   
   "pwd":"it123456"})

③. Delete user

The specified user can be deleted through the db.dropUser() function. Returns true after successful deletion. When deleting a user, it is necessary to switch to the database specified when creating the user. Note: You need to use an administrator user with the userAdminAnyDatabse role to delete other users. The itsxt user is in the sxt database, so you need to switch to the sxt database first.

db.dropUser("username")

db.dropUser("itxiong")

④. View user information

 show users

Other user actions

①, user authentication

By default, MongoDB does not enable user authentication. If we add users, we need to enable the user authentication mechanism. By modifying the mongodb.conf configuration file, add auth=true to the file. use

cd /usr/local/mongodb/etc/
vim mongodb.conf

# 修改内容
# 指定 db 路径
dbpath=/usr/local/mongodb/data/db
# 指定日志文件
logpath=/usr/local/mongodb/log/mongodb.log
# 配置端口
port=27017
# 配置允许访问
bind_ip=0.0.0.0
# 配置后置启动
fork=true
# 开启认证
auth=true
  • certified

db.auth('username','password')

If the result returns 1, it means the authentication is successful, and if it returns 0, it means the authentication failed. User can be queried after successful login

db.auth("itxiong","itxiong")

②. View the relationship between users and databases

We can view all user information in the admin library through the db.system.users.find() function.

db.system.users.find()

MongoDB collection (table)

A collection in MongoDB is a set of documents, which is equivalent to a table in a relational database

①, create a collection

MongoDB uses the db.createCollection() function to create collections.

  • Format: db.createCollection(name, options).
    1. name: The name of the collection to create.
    2. options: optional parameter, specify options about memory size and index.
field type describe
capped Boolean (optional) If true, creates a capped collection. A fixed collection is a collection with a fixed size that automatically overwrites the oldest documents when the maximum value is reached. When the value is true, the size parameter must be specified.
autoIndexId Boolean (Optional) If true, automatically create an index on the _id field. The default is false.
size value (Optional) Specify a maximum value (in bytes) for capped collections. If capped is true, this field also needs to be specified.
max value (Optional) Specifies the maximum number of documents contained in a capped collection.
  • default collection
db.数据库名.insert({
   
   'xx':'xxxx'})
  • without parameter set
db.createCollection("dev2")
  • with parameter set
db.createCollection("dev3",{capped:true,autoIndexId:true,size:2000000,max:1000})

②, delete collection

If we want to delete a collection, we need to switch to the database where the collection needs to be deleted, and use the drop() function to delete the collection.

  • Format: db.collection name.drop().
db.dev3.drop()

③, view collection

If you want to view existing collections, you can use the show collections or show tables command.

show collections

MongoDB document (collection data)

The data structure of documents in MongoDB is basically the same as JSON. All data stored in the collection is in BSON format.

document manipulation

①, Insert document

  • Format:
    1. Insert a single document:
      • db.collection name.insert(document).
      • db.setname.insertOne(document).
      • db.collection name.save(document).
    2. Insert multiple documents:
      • db.collection name.insert([{},{},{}…]).
      • db.collection name.save([{},{},{}…])
      • db.collection name.insertMany([{},{},{},…]).
  • test
  • single document
-- insert 函数
db.dev2.insert({title:'java',description:'编程语言',url:'www.baodu.com',tags:['file','io','string']})

-- insertOne 函数
db.dev2.insertOne({title:'css',description:'编程语言',url:'www.baodu.com',tags:['id','class','*']})

-- save 函数
db.dev2.save({title:'html',description:'编程语言',url:'www.baodu.com',tags:['p','div','span']})
  • multiple documents
-- insertMany 函数
db.dev2.insertMany([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])

②. Modify the document

MongoDB updates the documents in the collection through the update function or save function.

  • Format:

    1. Update all (clear): db.collection name.update({query condition},{update content},{update parameters (optional)})

    2. Operator update: db.collection name.update({query condition},{update operator:{update content}},{update parameter (optional)})

    3. Replace the source document: db.collection name.save({document})

      note\textcolor{red}{note}Note : The save() method replaces the existing document with the passed document.

-- update 函数
db.dev2.update({title:"xxx"},{title:"xxx"})

-- save 函数
db.dev2.save({_id: ObjectId("63a94e3e2371d5f083222b02"),title:"SpringCloud1",tags: [ "Spring Cloud Netflix", "Spring Cloud Consul" ] })
Update parameters
parameter effect
multi Implement batch updates. The default value is false, and the batch modification is changed to true
update operator
operator effect
$set Used to specify a key and update the key value, if the key does not exist and create it.
$inc You can increase or decrease a key whose value is a number in the document (it can only be a number that meets the requirements).
$unset Mainly used to delete keys.
$push Adds an array element to a key of an array type in the document, without filtering duplicate data. When the key exists when adding, it is required that the key-value type must be an array; if the key does not exist, an array-type key is created.
$pop Delete data elements. 1 means delete from the end of the array, -1 means delete elements from the head of the array
$pull Remove elements satisfying the condition from the array.
$pullAll Remove multiple elements from an array that satisfy a condition
$rename Rename the key.
  • the case
-- multi 批量修改
db.dev2.update({title:"java"},{$set:{title:"java学习",num:1}},{multi:true})

-- $set 操作符
db.dev2.update({title:"java"},{$set:{title:"java",tags:["spring","springmvc"]}})

-- $inc 操作符
db.dev2.update({title:"java学习"},{$inc:{num:5}})

-- $unset 操作符
db.dev2.update({title:"SpringCloud"},{$unset:{tags:[ "Spring Cloud Netflix"]}})

-- $push 操作符
db.dev2.update({title:"SpringCloud"},{$push:{tags:"Spring Data Redis"}})

-- $pop 操作符
db.dev2.update({title:"SpringCloud2"},{$pop:{tags:1}})
db.dev2.update({title:"SpringCloud2"},{$pop:{tags:-1}})

-- $pull 操作符
db.dev2.update({title:"SpringCloud4"},{$pull:{tags:"Spring Cloud Security"}})

-- $pullAll 操作符
db.dev2.update({title:"SpringCloud"},{$pullAll:{tags:[ "Spring Cloud Netflix"]}})

-- $rename 操作符
db.dev2.update({title:"SpringCloud"},{$rename:{tags:"tag"}})

③, delete the document

remove function

Use the remove() function to delete a specified document in a collection.

  • Format: db.collection name.remove({specified deletion condition},deletion parameter (optional parameter))

note\textcolor{red}{note}Note : The remove() method does not actually free up space. Need to continue executing db.repairDatabase() to reclaim disk space.

-- 指定条件删除
db.dev2.remove({title:"SpringCloud"})
db.repairDatabase()

-- 删除所有
db.dev2.remove({})
db.repairDatabase()
deleteOne function

The deleteOne() function is the official recommended method to delete documents. This method only deletes the first document that meets the condition.

  • Format: db.collection name.deleteOne({specified deletion condition})
-- 指定条件删除
db.dev2.deleteOne({title:"java学习"})
deleteMany function

The deleteMany function is the officially recommended deletion method. This method deletes all data that meets the condition.

  • Format: db.collection name.deleteMany({specified deletion condition})
-- 指定条件删除
db.dev2.deleteMany({title:"java学习"})

-- 删除所有
db.dev2.deleteMany({})

④, view the document

find() function

Documents can be queried in MongoDB using the find() function.

  • Format:
    • Method 1: db.collection name.find({query condition (optional)},{specified projection key (optional)})
    • Method 2 (projection): db.collection name.find({query condition},{projection key name: 1(display the column)|0(do not display the column),projection key name:1|0,...})
    • Method 3 (condition): db.collection name.find({key:{operator:condition}})
  • Notice:
    1. If no parameter is given, it means to query all data.
    2. p r e t t y ( ) \textcolor{Cyan}{pretty()} The pre tt y ( ) function can display all documents in a formatted way.
    3. l i m i t ( n u m ) \textcolor{Cyan}{limit(num)} The l imit ( n u m ) function reads the specified number of data records.
    4. s k i p ( n u m ) \textcolor{Cyan}{skip(num)} s ki p ( n u m ) skips the specified number of data
    5. Note that the query conditions cannot be placed in double quotes or single quotes when using fuzzy query.
query function
Function name effect
pretty() Functions can be used to display all documents in a formatted manner.
limit The function reads the specified num number of data records.
skip(num) Skip the specified num number of data
sort({sort key: 1}) Specify the field to sort by parameter. 1 for ascending order and -1 for descending order.
explain() View detailed query plan
fuzzy query parameters
condition effect
/^condition/ Use ^: to indicate the starting position
/condition$/ Use $: to indicate the end position.
/condition/ Content with condition
Projection Operation Parameters
parameter meaning example
1 show the column {projection key name: 1, projection key name: 1,...}
0 do not show this column {projection key name: 0, projection key name: 0,...}
incomplete 默认,不显示该列 ------------------------------------
条件操作符

条件操作符用于比较两个表达式并从 mongoDB 集合中获取数据。

操作符 名称 作用
$gt (>) 大于操作符 使用$gt 操作做大于的条件判断。该操作符可以数字或日期进行判断。
$lt (<) 小于操作符 使用$lt 操作做小于的条件判断。该操作符可以数字或日期进行判断。
$gte (>=)大于或等于操作符 使用$gte 操作做大于或等于的条件判断。该操作符可以数字或日期进行判断。
$lte (<=)小于或等于操作符 使用$lte 操作做小于或等于的条件判断。该操作符可以数字或日期进行判断。
$eq (==)等于操作符 使用$eq 操作做相等的条件判断。
$ne (!=)不等操作符 使用$ne 操作做不等的条件判断
$and find({$and:[{条件一},{,条件二},…]}) 使用$and 操作符来表示多条件间的并且关系。
$or find({$or:[{条件一},{条件二},…]}) 使用$or 操作符来表示多条件间的或者关系。
$type $type 操作符是基于 BSON 类型来检索集合中匹配的数据类型,并返回结果。
示例
-- 查询所有数据
db.dev2.find()

-- 格式化显示所有数据
db.dev2.find().pretty()

-- 查询指定数量的数据
db.dev2.find().limit(2)

-- 查询跳过指定数量的数据
db.dev2.find().skip(3)

-- 排序查询
db.dev2.find().sort({
   
   index:1})

-- 查询指定数据(格式化)
db.dev2.find({title:"html"}).pretty()

-- 模糊查询
db.dev2.find({title:/p/})
db.dev2.find({title:/^S/})
db.dev2.find({title:/1$/})

-- 投影操作
db.dev2.find({title:/S/},{_id:0,title:1,tags:1})

-- 条件操作符
-- $gt 操作符
db.dev3.find({size:{$gt:300}})

-- $lt 操作符
db.dev3.find({size:{$lt:300}})

-- $gte 操作符
db.dev3.find({size:{$gte:300}})

-- $lte 操作符
db.dev3.find({size:{$lte:300}})

-- $eq 操作符
db.dev3.find({size:{$eq:300}})

-- $ne 操作符
db.dev3.find({size:{$ne:300}})

-- $and 操作符
db.dev3.find({$and:[{size:{$gt:100}},{size:{$lt:300}}]})

-- $or 操作符
db.dev3.find({$or:[{size:{$gt:400}},{size:{$lt:200}}]})

-- $and和$or 综合
db.dev3.find({$or:[{$and:[{title:{$eq:"test5"}},{size:500}]},{size:{$lt:400}}]})

-- $type 操作符
db.dev3.find({title:{$type:"number"}})
findOne()函数
  • 格式:
    • 方式一:db.集合名.findOne({查询条件(可选)},{投影操作(可选)})
    • 方式二(投影):db.集合名.findOne({查询条件},{投影键名:1(显示该列)|0(不显示该列),投影键名:1|0,…})
    • 方式三(条件):db.集合名.findOne({键:{操作符:条件}})
  • 注意
    1. findOne()函数只返回满足条件的第一条数据。
    2. 未做投影操作该方法则自带格式化功能。
模糊查询参数
条件 作用
/^condition/ 使用^:表示起始位置
/condition$/ 使用$:表示结尾位置。
/condition/ 含有condition的内容
投影操作参数
参数 含义 示例
1 显示该列 {投影键名:1,投影键名:1,…}
0 不显示该列 {投影键名:0,投影键名:0,…}
未写全 默认,不显示该列 ------------------------------------
条件操作符

条件操作符用于比较两个表达式并从 mongoDB 集合中获取数据。

操作符 名称 作用
$gt (>) 大于操作符 使用$gt 操作做大于的条件判断。该操作符可以数字或日期进行判断。
$lt (<) 小于操作符 使用$lt 操作做小于的条件判断。该操作符可以数字或日期进行判断。
$gte (>=)大于或等于操作符 使用$gte 操作做大于或等于的条件判断。该操作符可以数字或日期进行判断。
$lte (<=)小于或等于操作符 使用$lte 操作做小于或等于的条件判断。该操作符可以数字或日期进行判断。
$eq (==)等于操作符 使用$eq 操作做相等的条件判断。
$ne (!=)不等操作符 使用$ne 操作做不等的条件判断
$and find({$and:[{条件一},{,条件二},…]}) 使用$and 操作符来表示多条件间的并且关系。
$or find({$or:[{条件一},{条件二},…]}) 使用$or 操作符来表示多条件间的或者关系。
$type $type 操作符是基于 BSON 类型来检索集合中匹配的数据类型,并返回结果。
示例
-- 查询第一条数据
db.dev2.findOne()

-- 模糊查询
db.dev2.findOne({title:/p/})
db.dev2.findOne({title:/^S/})
db.dev2.findOne({title:/1$/})

-- 投影操作
db.dev2.findOne({title:/c/},{_id:0,title:1,description:1,url:1})

-- 条件操作符
-- $gt 操作符
db.dev3.findOne({size:{$gt:300}})

-- $lt 操作符
db.dev3.findOne({size:{$lt:300}})

-- $gte 操作符
db.dev3.findOne({size:{$gte:300}})

-- $lte 操作符
db.dev3.findOne({size:{$lte:300}})

-- $eq 操作符
db.dev3.findOne({size:{$eq:300}})

-- $ne 操作符
db.dev3.findOne({size:{$ne:300}})

-- $and 操作符
db.dev3.findOne({$and:[{size:{$gt:100}},{size:{$lt:300}}]})

-- $or 操作符
db.dev3.findOne({$or:[{size:{$gt:400}},{size:{$lt:200}}]})

-- $and和$or 综合
db.dev3.findOne({$or:[{$and:[{title:{$eq:"test5"}},{size:500}]},{size:{$lt:400}}]})

-- $type 操作符
db.dev3.findOne({title:{$type:"number"}})

文档其他操作

①、变量定义

Mongo Shell 工具允许我们定义变量。所有的变量类型为 var 类型。也可忽略变量类型。变量中赋值符号后侧需要使用小括号来表示变量中的值。我们可以将变量作为任意插入文档的函数的参数。

  • 格式:
    1. 单个文档:变量名=({变量值})
    2. 多个文档:变量名=([{},{},{},…])
-- 定义变量 1
document=({title:'SpringCloud',tags:['Spring Cloud Netflix','Spring Cloud Security','Spring Cloud Consul']})
-- 定义变量 2
docu=([{title:'SpringCloud2',tags:['Spring Cloud Netflix','Spring Cloud Security','Spring Cloud Consul']},{title:'SpringCloud3',tags:['Spring Cloud Netflix','Spring Cloud Security','Spring Cloud Consul']},{title:'SpringCloud4',tags:['Spring Cloud Netflix','Spring Cloud Security','Spring Cloud Consul']}])
-- 使用变量
db.dev2.insert(document)
db.dev2.insert(docu)

MongoDB索引(文档索引)

索引操作

①、创建索引

在创建索引时,需要使用具有 dbAdmin 或者 dbAdminAnyDatabase 角色的用户。

  • 格式:db.集合名.createIndex({创建索引的键:排序规则,…},{创建索引的参数(可选参数)})
排序规则
规则 含义
1 按照升序规则创建索引
-1 按照降序规则创建索引。
参数
参数 数据类型 默认值 功能
background Boolean false 后台创建索引
unique Boolean false 创建唯一索引
name String 指定索引名称,如果未指定,MongoDB指挥满足过滤表达式的记录
partialFilterExpression document 如果指定MongoDB指挥满足过滤表达式的记录
sparse Boolean false 对文档中不存在的字段数据不启用索引
expireAfterSeconds integer 指定索引的过期时间
storageEngine document类型允许用户配置索引的存储引擎
-- 创建索引:1(升序)、background(后台创建索引)
db.dev3.createIndex({title:1},{background:true})

②、修改索引

MongoDB 没有单独的修改索引函数,如果要修改某个索引,需要先删除旧的索引,再创建新的索引。

③、删除索引

  1. 我们可以通过 d r o p I n d e x ( ) \textcolor{Cyan}{dropIndex()} dropIndex()函数来删除指定索引。
  2. 我们可以使用 d r o p I n d e x e s ( ) \textcolor{Cyan}{dropIndexes()} dropIndexes()函数删除集合中的全部索引,_id 键的索引除外。
  • 格式:
    1. 方式一:db.集合名.dropIndex(“索引名称”)。
    2. 方式二:db.集合名.dropIndexes()
-- 删除指定索引
db.dev3.dropIndex("title_1")

-- 删除全部索引
db.dev3.dropIndexes()

④、查看索引

  1. 我们可以通过 g e t I n d e x e s ( ) \textcolor{Cyan}{getIndexes()} getIndexes()或者 g e t I n d e x S p e c s ( ) \textcolor{Cyan}{getIndexSpecs()} getIndexSpecs()函数查看集合中的所有索引信息。
  2. 我们可以通过使用 g e t I n d e x K e y s ( ) \textcolor{Cyan}{getIndexKeys()} getIndexKeys()函数查看集合的索引键。
  3. 我们可以通过 t o t a l I n d e x S i z e ( ) \textcolor{Cyan}{totalIndexSize()} totalIndexSize()函数来查看当前集合中索引的大小,单位为字节。
  • 查看集合索引

    1. 方式一:db.集合名.getIndexse()
    2. 方式二:db.集合名.getIndexSpecs()
  • 查看索引键

    1. 格式:db.集合名.getIndexKeys();
  • 查看索引大小

    1. 格式:db.集合名.totalIndexSize([detail](可选参数))

      • 参数解释:

        detail 含义
        除 0 或 false 外的任意数据 显示该集合中每个索引的大小及集合中索引的总大小。
        0 或 false 只显示该集合中所有索引的总大小。默认值为 false。
-- 查看集合索引 getIndexes
db.dev3.getIndexes()

-- 查看集合索引 getIndexSpecs
db.dev3.getIndexSpecs()

-- 查看所有索引键
db.dev3.getIndexKeys()

-- 查看索引大小
db.dev3.totalIndexSize()
db.dev3.totalIndexSize([1])

-- 

索引类型

①、单字段索引

  1. 所谓单字段索引是指在 索引中只包含了一个键 \textcolor{red}{索引中只包含了一个键} 索引中只包含了一个键。查询时,可加速对该字段的各种查询请求,是最常见的索引形式。
  2. MongoDB 默认创建的_Id 索引也是这种类型。
  3. 我们可以使用createIndexes({索引键:排序规则})函数来创建单字段索引。
  • 格式:db.集合名.createIndex({索引键名:排序规则})
-- 创建单字段索引
db.dev3.createIndex({title:1},{background:true})

②、交叉索引

  1. 所谓交叉索引就是为一个集合的 多个字段分别建立索引 \textcolor{red}{多个字段分别建立索引} 多个字段分别建立索引,在查询的时候通过多个字段作为查询条件,这种情况称为交叉索引。
  2. 在查询文档时,在查询条件中包含一个交叉索引键或者在一次查询中使用多个交叉索引键作为查询条件都会触发交叉索引。
-- 创建交叉索引
db.dev3.createIndex({title:1},{background:true})
db.dev3.createIndex({size:1},{background:true})

③、复合索引

复合索引是单字段的升级版本,它针对 多个字段联合创建索引 \textcolor{red}{多个字段联合创建索引} 多个字段联合创建索引,先按第一个字段排序,第一个字段相同的文档按第二个字段排序,依次类推。

  • 格式:db.集合名.createIndex({索引键名:排序规则, 索引键名:排序规则,…});
-- 创建复合索引
db.dev3.createIndex({title:1,size:1})

④、多key索引

索引的字段为数组 \textcolor{red}{索引的字段为数组} 索引的字段为数组时,创建出的索引称为多 key 索引,多 key 索引会为数组的每个元素建立一条索引。

  • 格式:db.集合名.createIndex({数组键名:排序规则});
-- 创建多Key索引
db.dev3.createIndex({tags:1})

⑤、唯一索引

唯一索引会保证索引对应的键不会出现相同的值,比如_id 索引就是唯一索引。如果唯一索引所在字段有重复数据写入时,抛出异常。

  • 格式:db.集合名.createIndex({索引键名:排序规则},{unique:true})
-- 创建唯一索引:unique(唯一索引)
db.dev3.createIndex({title:1},{
   
   unique:true})

⑥、部分索引

  1. 部分索引是只针对符合某个特定条件的文档建立索引,3.2 版本才支持该特性。
  2. MongoDB 部分索引只为那些在一个集合中,满足指定的筛选条件的文档创建索引。由于部分索引是一个集合文档的一个子集,因此部分索引具有较低的存储需求,并降低了索引创建和维护的性能成本。
  3. 部分索引通过指定过滤条件来创建,可以为 MongoDB 支持的所有索引类型使用部分索引。
  • 格 式 : db.集合名.createIndex({ 索引键名 : 排 序 规则},{partialFilterExpression:{键名:{匹配条件:条件值}}})
-- 创建部分索引
db.dev3.createIndex({size:1},{partialFilterExpression:{size:{$gt:300}}})

⑦、稀疏索引

  1. 稀疏索引仅包含具有索引字段的文档的条目,即使索引字段包含空值也是如此。索引会跳过缺少索引字段的任何文档。
  2. 索引是“稀疏的”,因为它不包含集合的所有文档。相反,非稀疏索引包含集合中的所有文档,为那些不包含索引字段的文档存储空值。
  • 格式:db.集合名.createIndex({索引键名:排序规则},{sparse:true})
-- 创建稀疏索引
db.dev3.createIndex({tag:1},{sparse:true})

MongoDB正则查询

MongoDB 中查询条件也可以使用正则表达式作为匹配约束。

  • 格式
    1. 方式一:db.集合名.find({字段名:正则表达式});
    2. 方式二:db.集合名.find({字段名:{$regex:正则表达式,$options:正则选项}});
  • 正则表达式格式
    1. 表达式:/condition/正则选项

正则选项

正则选项 作用
i 不区分大小写以匹配大小写的情况。
m 多行查找,如果内容里面不存在换行符号或者条件上没有(start/end),该选项没有任何效果
x 设置 x 选项后,正则表达式中的非转义的空白字符将被忽略。需要$regex 与$options
s 允许点字符(即.)匹配包括换行符在内的所有字符。需要$regex 与$options 语法

运算逻辑符

逻辑符 作用
$in 字段满足条件1或条件2或条件3…的数据
$not 字段不满足条件的数据
$nin 字段不满足条件1或条件2或条件3…的数据

示例

-- ^:以条件开头,i:忽略大小写
-- 方式一
db.dev2.find({title:/^s/i})
-- 方式二
db.dev2.find({title:{$regex:/^s/i}})

-- $:以条件结尾,i:忽略大小写
-- 方式一
db.dev2.find({title:/G$/i})
-- 方式二
db.dev2.find({title:{$regex:/G/,$options:"i"}})

-- 包含
-- 方式一
db.dev2.find({title:/ing/})
-- 方式二
db.dev2.find({title:{$regex:/ing/}})

-- $in
db.dev2.find({title:{$in:[/^s/i,/^j/]}})

-- $not
db.dev2.find({title:{$not:/^s/i}})

-- $nin
db.dev2.find({title:{$nin:[/^s/i,/^c/]}})

MongoDB聚合查询

在 MongoDB 中我们可以通过 aggregate()函数来完成一些聚合查询,aggregate()函数主要用于处理诸如统计,平均值,求和等,并返回计算后的数据结果。

  • 格式:

    db.集合名.aggregate([
        {$group:
        	{_id:"$分组键名","$分组键名",...,别名:{聚合运算:"$运算列"}}
        },
        {条件筛选:
        	{键名:{运算条件:运算值}}
        }
    ])
    

聚合函数

mongodb聚合操作 含义 SQL函数
$match 查询集合有多少文档满足条件。 表聚合之前进行条件筛选。 where
$group 分组。 group by
$match 查询集合有多少文档满足条件。 表聚合之后进行条件筛选。 having
$project 使用$project 操作符做聚合投影操作。 select
$sort order by
$limit limit
$sum 集合中的所有指定键中的值的总和。(聚合运算) sum
$sum 查询集合中一共有多少个文档。(聚合运算) count
$lookup join

运算函数

函数 作用
$max 查询集合中指定键最大的文档。
$min 查询集合中指定键最小的文档。
$avg 查询集合中指定键的平均值
$push 查询集合,按照指定键(_id)分组并返回指定键($push),使用数组返回他们的指定键($push)。
$unwind 查询集合,将数组中的内容拆分显示。

示例

-- $sum:查询集合中一共有多少个文档
db.dev2.aggregate([{$group:{_id:null,count:{$sum:1}}}])

-- $sum:集合中的所有指定键中的值的总和
db.dev3.aggregate([{$group:{_id:$title,totalSize:{$sum:"$size"}}}])

-- $match:查询集合有多少文档满足条件
db.dev3.aggregate([{$match:{size:{$gt:200}}},{$group:{_id:null,totalSize:{$sum:1}}}])
db.dev3.aggregate([{$group:{_id:"$title",totalSize:{$sum:"$size"}}},{$match:{totalSize:{$gt:200}}}])

-- $max:查询集合中指定键最大的文档
db.dev3.aggregate([{$group:{_id:null,maxSize:{$max:"$size"}}}])

-- $min:查询集合中指定键最小的文档
db.dev3.aggregate([{$group:{_id:null,minSize:{$min:"$size"}}}])

-- $avg:查询集合中指定键的平均值
db.dev3.aggregate([{$group:{_id:null,maxSize:{$avg:"$size"}}}])

-- $push:查询集合,按照指定键(_id)分组并返回指定键($push),使用数组返回他们的指定键($push)。
db.dev3.aggregate([{$group:{_id:"$size",title:{$push:"$title"}}}])

-- $unwind
db.dev2.aggregate([{$unwind:"$tags"}])

聚合投影($project)

  • 格式:db.集合名.aggregate([{$unwind:“集合名”},{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …ect:{_id:0,别名:"键名",别名:“$键名”}}])
-- $project
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,tags:"$tags",title:"$title"}}])

是 ,对于中文要使用$substrCP

①、字符串操作

在$project 中我们可以通过 MongoDB 的字符串操作符对投影的内容做字符串处理。

操作符 作用
$toLower:“$键名” 将键的值转换为小写
$toUpper:“$键名” 将键的值转换为大写
$concat:[“$键名1”,“$键名2”…] 将键的值1与键的值2…的值拼接为新的字符串
$substr:[“$键名”,star,length] 将键的值从start开始截取截length,只能匹配 ASCII 的数据
$substrCP:[“$键名”,star,length] 将键的值从start开始截取截num位,可以匹配中文
  • 示例
-- $toLower:将键的值转换为小写,
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,New_Title:{$toLower:"$title"}}}])

-- $toUpper:将键的值转换为大写
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,New_Tags:{$toUpper:"$tags"}}}])

-- $concat:将字段1与字段2...的值拼接为新的字符串
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,Title_Tags:{$concat:["$title","-","$tags"]}}}])

-- $substr:将键的值从start开始截取截num位,只能匹配 ASCII 的数据
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,Title_Prefix:{$substr:["$title",0,3]}}}])

-- $substrCP:将键的值从start开始截取截num位,可以匹配中文
db.dev2.aggregate([{$unwind:"$tags"},{$project:{_id:0,Title_Prefix:{$substrCP:["$description",0,3]}}}])

②、算数运算

在$project 中我们可以通过 MongoDB 的算数作符对投影的内容做运算处理。

操作符 作用
$add:[“$键名”,n] 对键的值做加n处理
$subtract:[“$键名”,n] 对键的值做减n处理
$multiply:[“$键名”,n] 对键的值做乘n处理
$divide:[“$键名”,n] 对键的值做除n处理
$mod:[“$键名”,n] 对键的值做模n处理
  • 示例
-- $add:对键的值做加n处理
db.dev3.aggregate([{$project:{_id:0,title:1,New_Size:{$add:["$size",1]}}}])

-- $subtract:对键的值做减n处理
db.dev3.aggregate([{$match:{size:{$ne:null}}},{$project:{_id:0,title:1,New_Size:{$subtract:["$size",1]}}}])

-- $multiply:对键的值做乘n处理
db.dev3.aggregate([{$match:{size:{$ne:null}}},{$project:{_id:0,title:1,New_Size:{$multiply:["$size",3]}}}])

-- $divide:对键的值做除n处理
db.dev3.aggregate([{$match:{size:{$ne:null}}},{$project:{_id:0,title:1,New_Size:{$divide:["$size",2]}}}])

-- $mod:对键的值做模n处理
db.dev3.aggregate([{$match:{size:{$ne:null}}},{$project:{_id:0,title:1,New_Size:{$mod:["$size",3]}}}])

③、日期处理

MongoDB 中的时间会比系统当前时间少 8 个小时。因为他的时间是 UTC 的时间,而中国的时区是东八区,比 UTC 快 8 个小时,所以会比当前时间少 8 个小时。

  • 格式:
    1. 创建日期:
      • db.集合名.insert({date:new Date()})
      • db.集合名.insert({date:ISODate()})
    2. 查询日期:
      • db.集合名.find({time:{条件操作符:new Date(“yyyy-MM-ddThh:mm:ss”)}})
      • db.集合名.find({time:{条件操作符:ISODate(“yyyy-MM-ddThh:mm:ss”)}})
创建日期
-- 创建当前日期
db.dev3.insert({
   
   date:new Date()})

-- 创建指定日期:日期格式为 yyyy-MM-ddThh:mm:ss
-- 方式一
db.dev3.insert({
   
   time:new Date("2022-12-27T15.52:33")})
-- 方式二
db.dev3.insert({
   
   time:ISODate("2022-12-27T15:57:00")})
查询日期
显示:年-月-日
操作符 作用
{$year:“$日期键”} 显示年份
{$month:“$日期键”} 显示月份
{$dayOfMonth:“$日期键”} 显示日期
  • 示例
-- 显示年份
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{年份:{$year:"$birth"}}}])

-- 显示月份
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{月份:{$month:"$birth"}}}])

-- 显示日期
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{月份:{$dayOfMonth:"$birth"}}}])
显示:时-分-秒-毫秒
操作符 作用
{$hour:“$日期键”} 显示小时
{$minute:“$日期键”} 显示分钟
{$second:“$日期键”} 显示秒
{$millisecond:“$日期键”} 显示毫秒
  • 示例
-- 显示小时
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{小时:{$hour:"$birth"}}}])

-- 显示分钟
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{分钟:{$minute:"$birth"}}}])

-- 显示秒
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{秒:{$second:"$birth"}}}])
 
-- 显示毫秒
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{毫秒:{$millisecond:"$birth"}}}])
显示:第几天

一周星期几、一年第几周、一年第几天

操作符 作用
{$dayOfWeek:“$日期键”} 星期日为 1,星期六为 7。
{$week:“$birth”} 全年的周计数从 0 开始。
{$dayOfYear:“$birth”} 全年中的第几天。
  • 示例
-- 显示一周中的星期几,星期日为 1,星期六为 7。
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{星期:{$dayOfWeek:"$birth"}}}])

-- 显示一年中的第几周,全年的周计数从 0 开始。
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{第几周:{$week:"$birth"}}}])

-- 显示一年中的第几天,全年中的第几天。
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{第几天:{$dayOfYear:"$birth"}}}])
显示自定义日期格式
  • 格式:$dateToString:{format:“%Y 年%m 月%d 日 %H:%M:%S”,date:“birth”}
  • 示例
db.dev3.aggregate([{$match:{name:"admin"}},{$project:{年份:{$dateToString:{format:"%Y年%m月%d日 %H:%M:%S",date:"$birth"}}}}])
  • 格式表
字符 含义 取值范围
%Y Year(4 digits,zero padded) 0000-9999
%m Month(2 digits,zero padded) 01-12
%d Day of Month(2 digits,zero padded) 01-31
%H Hour(2 digits,zero padded,24-hour clock) 00-23
%M Minute(2 digits,zero padded) 00-59
%S Second(2 digits,zero padded) 00-60
%L Millisecond(3 digits,zero padded) 000-999
%j Day of year(3 digits,zero padded) 001-366
%w Day of week(1-Sunday,7-Saturday) 1-7
%U Week of year(2 digits,zero padded) 00-53

二、Maven使用MongoDB

version1.0

导入依赖

<!-- mongodb依赖 -->
<dependency>
 	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>3.12.11</version>
</dependency>

配置连接方式工具

①、不使用连接池

数据库直连
  • 修改参数
    1. ip地址、端口
  • 使用工具类
    1. getCollection(String dbName, String collName)
      • 数据库名
      • 集合名
public class MongoDBUtil {
    
    
    private static MongoClient client = null;

    /**
     * MongoDB连接参数:
     * 1. ip地址;
     * 2. 端口
     */
    static{
    
    
        if(client == null){
    
    
            client = new MongoClient("192.168.66.11",27017);
        }
    }

    /**
     * 获取 MongoDB 数据库
     * @param dbName
     * @return
     */
    public static MongoDatabase getDatabase(String dbName){
    
    
        return client.getDatabase(dbName);
    }

    /**
     * 获取 MongoDB 中的集合
     * @param dbName
     * @param collName
     * @return
     */
    public static MongoCollection getCollection(String dbName, String collName){
    
    
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    
    /**
     * 删除 MongoDB 中的集合
     * @param dbName
     * @param collName
     */
    public static void dropCollection(String dbName, String collName) {
    
    
        MongoCollection coll = getCollection(dbName, collName);
        coll.drop();
    }
}
用户认证连接

创建 MongoDB 拦截-使用用户认证

  • 修改参数
    1. 用户名、数据库名、用户密码
    2. ip地址、端口
  • 使用工具类
    1. getCollection(String dbName, String collName)
      • 数据库名
      • 集合名
public class MongoDBAuthUtil {
    
    
    private static MongoClient client = null;

    /**
     * MongoDB连接参数
     * 1. 用户名、数据库名、用户密码
     * 2. ip地址、端口
     */
    static {
    
    
        if (client == null) {
    
    
            //创建一个封装用户认证信息
            MongoCredential credential = MongoCredential.createCredential("admin", "dev1", "xiongPassWord".toCharArray());
            //封装 MongoDB 的地址与端口
            ServerAddress address = new ServerAddress("192.168.66.11", 27017);
            client = new MongoClient(address, Arrays.asList(credential));
        }
    }
    
    /**
     * 获取 MongoDB 数据库
     * @param dbName
     * @return
     */
    public static MongoDatabase getDatabase(String dbName) {
    
    
        return client.getDatabase(dbName);
    }

    /**
     * 获取 MongoDB 中的集合
     * @param dbName
     * @param collName
     * @return
     */
    public static MongoCollection getCollection(String dbName, String collName) {
    
    
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    
    /**
     * 删除 MongoDB 中的集合
     * @param dbName
     * @param collName
     */
    public static void dropCollection(String dbName, String collName) {
    
    
        MongoCollection coll = getCollection(dbName, collName);
        coll.drop();
    }
}

②、使用连接池

数据库池连

使用池连的方式获取连接

  • 修改参数
    1. ip地址、端口
  • 使用工具类
    1. getCollection(String dbName, String collName)
      • 数据库名
      • 集合名
public class MongoDBPoolUtil {
    
    
    private static MongoClient client = null;

    /**
     * MongoDB连接参数:
     * 1. ip地址;
     * 2. 端口
     */
    static{
    
    
        if(client == null){
    
    
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            builder.connectionsPerHost(10);//每个地址的最大连接数
            builder.connectTimeout(5000);//连接超时时间
            builder.socketTimeout(5000);//设置读写操作超时时间
            ServerAddress address = new ServerAddress("192.168.66.11",27017);
            client = new MongoClient(address,builder.build());
        }
    }
    
    /**
     * 获取数据库数据源
     * @param dbName
     * @return
     */
    public static MongoDatabase getDatabase(String dbName){
    
    
        return client.getDatabase(dbName);
    }
    
    /**
     * 获取数据库连接对象
     * @param dbName
     * @param collName
     * @return
     */
    public static MongoCollection getCollection(String dbName, String collName){
    
    
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    
    /**
     * 删除 MongoDB 中的集合
     * @param dbName
     * @param collName
     */
    public static void dropCollection(String dbName, String collName) {
    
    
        MongoCollection coll = getCollection(dbName, collName);
        coll.drop();
    }
}
用户认证池连

支持用户认证的池连

  • 修改参数
    1. 用户名、数据库名、用户密码
    2. ip地址、端口
  • 使用工具类
    1. getCollection(String dbName, String collName)
      • 数据库名
      • 集合名
public class MongoDBAuthPoolUtil {
    
    
    private static MongoClient client = null;
    
    /**
     * MongoDB连接参数
     * 1. 用户名、数据库名、用户密码
     * 2. ip地址、端口
     */
    static {
    
    
        if (client == null) {
    
    
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            builder.connectionsPerHost(10);//每个地址的最大连接数
            builder.connectTimeout(5000);//连接超时时间
            builder.socketTimeout(5000);//设置读写操作超时时间
            MongoCredential credential = MongoCredential.createCredential("admin", "develop", "itxiongpwd".toCharArray());
            ServerAddress address = new ServerAddress("192.168.66.11", 27017);
            client = new MongoClient(address, credential, builder.build());
        }
    }

    /**
     * 获取 MongoDB 数据库
     * @param dbName
     * @return
     */
    public static MongoDatabase getDatabase(String dbName) {
    
    
        return client.getDatabase(dbName);
    }

    /**
     * 获取 MongoDB 中的集合
     * @param dbName
     * @param collName
     * @return
     */
    public static MongoCollection getCollection(String dbName, String collName) {
    
    
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    
    /**
     * 删除 MongoDB 中的集合
     * @param dbName
     * @param collName
     */
    public static void dropCollection(String dbName, String collName) {
    
    
        MongoCollection coll = getCollection(dbName, collName);
        coll.drop();
    }
}

Mongo操作

操作集合

①、创建集合

createCollection(String collectionName):创建集合

    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取数据库
        MongoDatabase adminDB = MongoDBUtil.getDatabase("admin");
        // 2. 创建集合
        adminDB.createCollection("dev5");
        System.out.println("创建成功~~~~~~");
    }
②、获取集合

通过工具类获取集合

    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev5 = MongoDBUtil.getCollection("admin", "dev5");
        // 2. 获取集合名
        System.out.println(dev5.getNamespace());
    }
③、删除集合

通过工具类删除集合

    public static void main(String[] args) {
    
    
        // 1. 通过工具类删除集合
        MongoDBUtil.dropCollection("admin","dev1");
    }

操作文档

创建文档
  • 单个文档
  1. new Document():创建一个文档
    • append(String key,Object value):为文档添加信息
  2. insertOne:新增单个文档
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 创建 Document 文档
        /**
         * 1. 创建文档:new Document();
         * 2. 添加文档信息:append(String key,Object value)
         */
        Document docu = new Document();
        docu.append("username","ls")
                .append("userage",26)
                .append("userdesc","very goog")
                .append("userlike",Arrays.asList(new String[]{
    
    "Music","Sport"}));
        // 3. 添加文档到集合中
        dev4.insertOne(docu);
    }
  • 多个文档
  1. new Document():创建一个文档
    • append(String key,Object value):为文档添加信息
  2. insertMany:新增多个文档
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 创建 Document 文档
        /**
         * 1. 创建文档:new Document()集合;
         * 2. 添加文档信息:append(String key,Object value)
         */
        List<Document> docus = new ArrayList<Document>();
        for (int i = 0; i < 5; i++) {
    
    
            Document docu = new Document();
            docu.append("username","ls"+i)
                    .append("userage",26+i)
                    .append("userdesc","very goog"+i)
                    .append("userlike",Arrays.asList(new String[]{
    
    "Music","Sport"}));
            docus.add(docu);
        }
        // 3. 添加文档到集合中
        dev4.insertMany(docus);
    }
更新文档
更新单个文档
  • 单个键
  1. new Document():文档、条件
  2. updateOne:更新一个文档
  3. Filters:mongodb自带的条件过滤器
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 更新文档
        /**
         * Filters封装了条件的一个工具类
         */
        dev4.updateOne(Filters.eq("username","ls"),new Document("$set",new Document("userage",26)));
    }
  • 多个键
  1. new Document():文档、条件
  2. updateOne:更新一个文档
  3. Filters:mongodb自带的条件过滤器
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 更新文档
        /**
         * Filters封装了条件的一个工具类
         */
        dev4.updateOne(Filters.eq("username","ls0"),new Document("$set",new Document("userage",18).append("userdesc","Very Good")));
    }
更新多个文档
  • 单个建
  1. new Document():文档、条件
  2. updateMany:更新多个文档
  3. Filters:mongodb自带的条件过滤器
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 更新文档
        /**
         * Filters封装了条件的一个工具类
         */
        dev4.updateMany(Filters.ne("username",null),new Document("$set",new Document("userdesc","Very Good")));
    }
  • 多个键
  1. new Document():文档、条件
  2. updateMany:更新多个文档
  3. Filters:mongodb自带的条件过滤器
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 更新文档
        /**
         * Filters封装了条件的一个工具类
         */
        dev4.updateMany(Filters.ne("username",null),new Document("$set",new Document("userdesc","OK").append("userage",20)));
    }
更新文档中的数组
  1. new Document():文档、条件
  2. updateMany/updateOne:更新文档
  3. Filters:mongodb自带的条件过滤器
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 更新文档
        /**
         * Filters封装了条件的一个工具类
         */
        dev4.updateOne(Filters.eq("username","ls"),new Document("$push",new Document("userlike","Art")));
    }
查询文档
查看全部文档
  1. collection.find():获取所有集合迭代器
  2. iterable.iterator():迭代器转换
    • hasNext:是否存在
    • next:获取文档
  3. docu.get(“key”):获取文档中的信息
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find();
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }
根据_id查询文档
  1. collection.find(条件):获取所有集合迭代器
  2. new ObjectId():id对象
  3. iterable.iterator():迭代器转换
  • hasNext:是否存在
  • next:获取文档
  1. docu.get(“key”):获取文档中的信息
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.eq("_id",new ObjectId("63aad42c22371f29b10f025c")));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }
查询多个文档
  • Filters
    1. gt:大于
    2. type:类型
    3. in:在集合内
    4. nin:不在集合内
  • 非正则
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.gt("userage", 19));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }
  • 正则

Filters

  1. regex:正则的键
  2. Pattern.compile(“正则表达式”):正则表达式不加 //
 public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.regex("username", Pattern.compile("^l.*2$")));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }
  • 逻辑运算符

Filters

  1. and
  2. or
  3. sort
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.and(Filters.eq("username","ls2"),Filters.eq("userage",20)));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }
  • 排序查询
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev4");
        // 2. 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.regex("username", Pattern.compile("4$"))).sort(new Document("username",-1));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }

操作日期

日期工具类
public class DateUtil {
    
    
    /**
     * Date To String
     * @param pattern
     * @param date
     * @return
     */
    public static String dateToString(String pattern, Date date){
    
    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    /**
     * String To Date
     * @param pattern
     * @param date
     * @return
     */
    public static Date stringToDate(String pattern, String date){
    
    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date d = null;
        try{
    
    
            d = simpleDateFormat.parse(date);
        }catch(Exception e){
    
    
            e.printStackTrace();
        }
        return d;
    }
}
插入日期
  • 插入系统当前日期
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev5 = MongoDBUtil.getCollection("admin", "dev5");
        Document docu = new Document();
        docu.append("username","ww")
                .append("userage",22)
                .append("userdesc","Very Good")
                .append("userlike", Arrays.asList(new String[]{
    
    "Music","Art"}))
                .append("userbirth",new Date());
        dev5.insertOne(docu);
    }
  • 插入指定日期
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev5 = MongoDBUtil.getCollection("admin", "dev5");
        // 2. 通过工具类获取自定义日期
        Date date = DateUtil.stringToDate("yyyy-MM-dd HH:mm:ss", "2022-05-01 13:33:11");
        Document docu = new Document();
        docu.append("username","zl")
                .append("userage",24)
                .append("userdesc","Very Good")
                .append("userlike", Arrays.asList(new String[]{
    
    "Music","Art"}))
                .append("userbirth",date);
        dev5.insertOne(docu);
    }
查询日期

Filters

  1. eq:等于
  2. gt:大于
    public static void main(String[] args) {
    
    
        // 1. 根据工具类获取集合
        MongoCollection dev4 = MongoDBUtil.getCollection("admin", "dev5");
        // 2. 通过工具类获取日期
        Date date = DateUtil.stringToDate("yyyy-MM-dd HH:mm:ss", "2022-12-28 13:32:13");
        // 获取文档的迭代器
        FindIterable<Document> iterable = dev4.find(Filters.eq("userbirth",date));
        MongoCursor<Document> cursor = iterable.iterator();
        // 3. 遍历获取文档信息
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println("username:"+docu.get("username"));
            System.out.println("userage:"+docu.get("userage"));
            System.out.println("userdesc:"+docu.get("userdesc"));
            System.out.println("userlike:"+docu.get("userlike"));
            System.out.println("##############################");
        }
    }

聚合操作

普通查询
  1. new Document():相当于{}
  2. aggregate:聚合操作
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev5 = MongoDBUtil.getCollection("admin", "dev5");
        // 2. 创建aggregate
        Document sum = new Document();
        sum.append("$sum",1);
        Document count = new Document();
        count.append("_id",null).append("count",sum);
        Document group = new Document();
        group.append("$group",count);
        // 3. 创建容器
        List<Document> list = new ArrayList<Document>();
        list.add(group);
        // 4. 通过集合获取聚合操作数据
        AggregateIterable iterable = dev5.aggregate(list);
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println(docu.get("count"));
        }
    }
聚合投影约束
  1. new Document():相当于{}
  2. aggregate:聚合操作
    public static void main(String[] args) {
    
    
        // 1. 通过工具类获取集合
        MongoCollection dev2 = MongoDBUtil.getCollection("admin", "dev2");
        // 2. 创建aggregate
        Document unwind = new Document();
        unwind.append("$unwind","$tags");
        Document pro = new Document();
        pro.append("_id",0).append("tags","$tags").append("title","$title");
        Document project = new Document();
        project.append("$project",pro);
        // 3. 创建容器
        List<Document> list = new ArrayList<Document>();
        list.add(unwind);
        list.add(project);
        // 4. 通过集合获取聚合操作数据
        AggregateIterable iterable = dev2.aggregate(list);
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println(docu);
        }
    }

分页操作

  • 使用 skip 与 limit 方法分页
    public static void main(String[] args) {
    
    
        // 1. 创建分页条件
        int pageIndex = 2;
        int page = (pageIndex - 1) * 2;
        // 2. 通过工具类获取集合
        MongoCollection dev3 = MongoDBUtil.getCollection("admin", "dev3");
        // 3. 通过集合获取集合文档数
        Document condition = new Document("size", new Document("$ne", null));
        long countNum = dev3.countDocuments(condition);
        System.out.println(countNum);
        // 4. 分页查询
        FindIterable iterable = dev3.find(condition).skip(page).limit(2);
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
    
    
            Document docu = cursor.next();
            System.out.println(docu);
        }
    }
  • 优化分页查询

        public static void main(String[] args) {
          
          
            // 1. 创建分页条件
            /**
             * int pageIndex = 2;
             * int pageSize = 3;
             * String lastId = "";
             */
            int pageIndex = 2;
            int pageSize = 3;
            String lastId = "63a976244d18206c11b226a2";
            // 2. 通过工具类获取集合
            MongoCollection dev3 = MongoDBUtil.getCollection("admin", "dev3");
            // 3. 通过集合获取集合文档数
            Document condition = new Document("size", new Document("$ne", null));
            long countNum = dev3.countDocuments(condition);
            System.out.println(countNum);
            // 4. 分页查询
            FindIterable iterable = null;
            if(pageIndex == 1){
          
          
                iterable = dev3.find(condition).limit(pageSize);
            }else {
          
          
                if (lastId != null) {
          
          
                    condition.append("_id",new Document("$gt",new ObjectId(lastId)));
                    iterable = dev3.find(condition).limit(pageSize);
                }
            }
            MongoCursor<Document> cursor = iterable.iterator();
            while (cursor.hasNext()) {
          
          
                Document docu = cursor.next();
                System.out.println(docu);
            }
        }
    

version1.0

Guess you like

Origin blog.csdn.net/qq_56571862/article/details/128998222