mongodb语法

参考文档:https://docs.mongodb.com/manual/reference/

BSON Types

BSON Type有2种标识符,整形和字符串

类型 数值 字符串 说明
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”

可以使用***$type***操作符使用这些类型。

BSON特定类型

ObjectId

近似唯一,快速生成,已排序的类型,12byte**。**

String

UTF-8格式,

Timestamps

Date

64位整形,从1970.01.01开始的毫秒数。

查询和投影操作符

Name 意义
比较操作符
$eq 相等
$gt 大于
$gte 大于等于
$in 包含在集合中
$lt 小于
$lte 小于等于
$ne 不等于
$nin 不在集合中
逻辑操作符
$and AND
$not NOT
$nor 同时满足2个条件的,则为false
$or OR
元素操作符
$exists 字段存在
$type 字段类型为指定类型
表达式计算
$expr
$jsonSchema
$mod
$regex 正则表达式
$text
$where
地理空间
$geoIntersects
$geoWithin
$near
$nearSphere
数组操作符
$all 包含所有指定的元素
$elemMatch 存在元素匹配所有指定条件
$size 指定数组大小
二进制操作
$bitsAllClear
$bitsAllSet
$bitsAnyClear
$bitsAnySet
注释
$comment
投影
$ 投影第一个数组元素
$elemMatch 投影第一个匹配条件的元素
$meta
$slice

Update操作

操作符 说明 语法
字段操作
$currentDate 设置字段值为当前日期
$inc 字段值加上指定值
$min 仅当指定值小于字段值时更新
$max 仅当指定值大于字段值时更新
$mul 字段值乘以指定值
$rename 字段重命名
$set 设置字段值为指定值
$setOnInsert 当文档新增时设置值。
$unset 移除字段值
数组操作
$ 代指匹配查询条件的第一个元素
$[] 代指匹配查询条件的所有元素
$[] 代指匹配arrayFilters的所有元素
$addToSet 如果元素不存在则加入数组
$pop 移除第一或最后的元素
$pull 移除匹配条件的所有元素
$push 增加一个元素到数组
$pullAll 移除匹配一个集合的所有元素
修饰
$each 修饰push,push,push,addToSet,循环数组中的每个元素当做一个对象,而不是整个数组作为一个对象
$position 修饰$push,指定插入位置
$slice 修饰$push,限制修改数组的大小
$sort 修饰$push,排序数组
位运算
$bit Performs bitwise AND, OR, and XOR updates of integer values.

聚合管道阶段

MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。

集合聚合

db.collection.aggregate()

除了$out, $merge, and $geoNear,所有阶段都可以出现多次。

Stage Description 示例
$addFields 增加新字段到文档中,类似project。project。project。set is an alias for $addFields.
$bucket
$bucketAuto
$collStats
$count 文档总数
$facet
$geoNear 输出接近某一地理位置的有序文档
$graphLookup
$group 分组 { $group: { _id: null, count: { $sum: 1 } } }
$indexStats
$limit 取n条记录 { $limit : 5 }
$listSessions
$lookup 从另外一个文档引入字段
$match 用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。 { $match : { score : { $gt : 70, $lte : 90 } } }
$merge 把结果输出到指定collection
$out 把结果输出到指定collection { $out: “” }
$planCacheStats
$project 修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。 $project : { title : 1,author : 1 ,}
$redact
$replaceRoot 用replacementDocument代替当前文档 { $replaceWith: }
$replaceWith 同$replaceRoot
$sample 随机取样 { $sample: { size: 3 } }
$set 增加字段 { $set: { : , … } }
$skip 跳过n条记录 { $skip : 5 }
$sort 排序 { $sort : { age : -1, posts: 1 } }
$sortByCount 分组count,再倒序 { sortByCount:"sortByCount: "sortByCount:"tags" } 等价于: { $group: { _id: , count: { $sum: 1 } } }, { $sort: { count: -1 } }
$unset 排除字段 { $unset: [ “”, “”, … ] }
$unwind 把数组属性平铺,1条记录会平铺成n条记录 {$unwind: { path: , includeArrayIndex: , //保存元素索引的新字段 preserveNullAndEmptyArrays: //true:path为null, missing,empty array,输出文档。false:不输出 } }

数据库聚合

db.aggregate( [ { <stage> }, ... ] )

since 3.6

聚合管道操作(标量函数)

Name Description 示例
数学计算
$abs 求绝对值
$add 加法
$ceil 大于等于指定值的最小整数
$divide 除法
$exp 指数
$floor 小于等于指定值的最大整数
$ln 自然对数
$log 对数
$log10 10为底对数
$mod 求模
$multiply 乘法
$pow 求幂
$round round
$sqrt 求二次根
$subtract 减法
$trunc 截断
数组操作
$arrayElemAt 求index
$arrayToObject 数组转document
$concatArrays 连接数组
$filter 过滤
$in 在集合中
$indexOfArray 第一个匹配的index
$isArray 是否数组
$map map
$objectToArray 对象转数组
$range
$reduce
$reverseArray
$size 数组大小
$slice 数组切片
$zip 合并2个数组
逻辑表达式
$and and
$not not
$or or
比较操作符
$cmp *比较**2**个操作数*
$eq 相等
$gt 大于
$gte 大于等于
$lt 小于
$lte 小于等于指定值的最大整数
$ne 不等
条件操作符
Name Description
$cond
$ifNull
$switch
日期操作
$dateFromParts
$dateFromString
$dateToParts
$dateToString
$dayOfMonth
$dayOfWeek
$dayOfYear
$hour
$isoDayOfWeek
$isoWeek
$isoWeekYear
$millisecond
$minute
$month
$second
$toDate
$week
$year
$add
$subtract
字面表达式
$literal
对象表达式
$mergeObjects
$objectToArray
集合操作
$allElementsTrue
$anyElementTrue
$setDifference
$setEquals
$setIntersection
$setIsSubset
$setUnion
字符串操作
$concat
$dateFromString
$dateToString
$indexOfBytes
$indexOfCP
$ltrim
$regexFind
$regexFindAll
$regexMatch
$rtrim
$split
$strLenBytes
$strLenCP
$strcasecmp
$substr
$substrBytes
$substrCP
$toLower
$toString
$trim
$toUpper
文本操作
$meta
三角 函数
$sin
$cos
$tan
$asin
$acos
$atan
$atan2
$asinh
$acosh
$atanh
$degreesToRadians
$radiansToDegrees
类型操作
$convert Converts a value to a specified type.(since4.0)
$toBool Converts value to a boolean.(since4.0)
$toDate Converts value to a Date.(since4.0)
$toDecimal Converts value to a Decimal128.(since4.0)
$toDouble Converts value to a double.(since4.0)
$toInt Converts value to an integer.(since4.0)
$toLong Converts value to a long.(since4.0)
$toObjectId Converts value to an ObjectId.(since4.0)
$toString Converts value to a string.(since4.0)
$type Return the BSON data type of the field.
聚合操作
$addToSet
$avg
$first
$last
$max
$mergeObjects
$min
$push
$stdDevPop
$stdDevSamp
$sum
Accumulators (in Other Stages)
$avg
$max
$min
$stdDevPop
$stdDevSamp
$sum
变量操作
$let

spring实现

文档结构

{
_id: ObjectId(“5dbbe8ce79829800070b2374”),
SMD: {
source: {
DSN: “XXXX”,
KEY: “5da31fa07c2a5e497e8ded8c844e38bd”
},
infofragment: [
{
storagetype: “inner”,
format: “origin”,
filestore: {
fsname: “爬虫”,
filename: “XXXXX基本数据表”,
fileid: “5dbbe8ce79829800070b2373”
},
adapter: { }
}
],
services: [
{
name: “DataImport”,
handledtime: ISODate(“2019-11-01T08:11:58.369Z”),
version: “1.0”
},
{
name: “TagIdentify”,
handledtime: ISODate(“2020-03-01T13:30:41.006Z”)
}
],
quality: {
status: NumberInt(“1”),
checktime: ISODate(“2020-03-01T13:47:38.289Z”),
version: “EPModel:1”
},
timestamp: ISODate(“2020-03-01T13:30:41.007Z”),
tenantid: “XXXX”
},
UMD: {
creator: null,
bd: “XXXXXX”,
ru: null,
pt: “XXXXX基本数据表”,
bw: “XXXXXX”,
bot: “井”,
root: null,
createdate: null,
publisher: null,
title: “XXXXX基本数据表”,
bo: “”,
bp: “XXXX”,
ds: “XXXXX”
},
version: NumberInt(“42702”)
}

说明:

UMD下属性是不固定的。

查询

1、通过json字符串构造查询对象

Document filter = Document.parse(filter.toJSONString(0));
String collectionName = mongoTemplate.getCollectionName(AppData.class);
MongoCollection collection = mongoTemplate.getCollection(collectionName);long count = collection.countDocuments(filter);FindIterable<Document> found = collection.find(filter);

2、正则表达式

            Document doc = new Document();doc.put("$regex", request.getTitle());doc.put("$options", "i");filter.put(PATH_UMD_TITLE, doc);或者criteriaAll.and(AppData.PATH_UMD_PT).regex(request.getPt(), "i");

聚合

1、根据Services.name作为分组条件,统计数据,services元素展开

// { "$unwind" : "$SMD.services"}
UnwindOperation unwindOperation = Aggregation.unwind("SMD.services");Criteria criteria = Criteria.where(AppData.PATH_SMD_TENANT).is(tenantId);
MatchOperation matchOperation = Aggregation.match(criteria);//{ "$project" : { "servicename" : "$SMD.services.name" }}
ProjectionOperation projectionOperation = Aggregation.project().and("SMD.services.name").as("servicename");
//{ "$group" : { "_id" : { "servicename" : "$servicename"} , "total" : { "$sum" : 1}}}
GroupOperation groupOperation = Aggregation.group("servicename"
).count().as("total");//========统计所有记录
Aggregation aggregationAll = Aggregation.newAggregation(matchOperation, unwindOperation, projectionOperation, groupOperation, Aggregation.project("servicename", "total").and("servicename").previousOperation()
);AggregationResults resultAll = mongoTemplate.aggregate(aggregationAll, AppData.class, ServiceCountEntity.class);List<ServiceCountEntity> valuesAll = resultAll.getMappedResults();return valuesAll.stream().collect(Collectors.toMap(ServiceCountEntity::getServiceName, ServiceCountEntity::getTotal));

2、根据UMD指定的字段统计

Criteria criteria = Criteria.where(AppData.PATH_SMD_TENANT).is(tenantId);String path = StrUtil.format("UMD.{}", tag);GroupBy groupBy = GroupBy.key(path).initialDocument("{}").reduceFunction("function(doc, prev){}");GroupByResults r = mongoTemplate.group(criteria, mongoTemplate.getCollectionName(AppData.class), groupBy, BasicDBObject.class);
List<Document> valuesAll = (List<Document>) r.getRawResults().get("retval");return valuesAll.size();

修改

1、通过id查询文档,并修改UMD属性

Criteria criteriaId = Criteria.where("_id").is(new ObjectId(id));
Query query = new Query(criteriaId);Update update = new Update();//更新UMD
for (Map.Entry<String, Object> entry : umd.entrySet()) {update.set(StrUtil.format("UMD.{}", entry.getKey()), entry.getValue());
}mongoTemplate.updateFirst(query, update, AppData.class);

2、修改Services下元素,通过name匹配,如果不存在则插入元素

Criteria criteriaId = Criteria.where("_id").is(new ObjectId(id));
Query query = new Query(criteriaId);Document service = new Document();
service.put("name", "TagIdentify");Update update = new Update();
//删除一个匹配的数组元素
update.pull("SMD.services",service);//先更新一次,如果service存在(name相同),则删除。
mongoTemplate.updateFirst(query, update, AppData.class);service.put("handledtime", new Date());
service.put("version", "1.0");Update updateAdd = new Update();
//新增服service
updateAdd.addToSet("SMD.services", service);mongoTemplate.updateFirst(query, updateAdd, AppData.class);

mongodb语法与spring实现相关推荐

  1. MongoDB语法学习

    MongoDB语法学习 MongoDB官方文档 mongodb语法有很多,如多列索引,查询时可以统计函数,支持多条件查询,但是目前对于多表的查询是暂不支持的,但是可以通过数据冗余来解决多表查询的问题. ...

  2. MongoDB语法与现有关系型数据库SQL语法比较

    MongoDB语法与现有关系型数据库SQL语法比较 MongoDB语法 MySql语法 db.test.find({'name':'foobar'}) select * from test where ...

  3. python操作mongodb语法_python 操作MongoDB

    安装MongoDB 启动数据库:安装完成指定数据库存放路径 mongod.exe --dbpath c:\data\db 进入目录后运行mongo.exe 成功 创建数据库 >use mydb ...

  4. MongoDB:使用Spring数据添加计数器

    在我的博客应用程序中,您可以查看任何用户的个人资料,例如,我的个人资料页面将为http://www.jiwhiz.com/profile/user1,"user1"是我在系统中的用 ...

  5. MongoDB语法案例

    文章目录 基本语法 基本查询 1. find 聚合查询 案例1. 类似not in的实现 基本语法 mongoDB 聚合查询语法,这些命令均在 Aggregation 中实现 $project:修改输 ...

  6. MongoDB 语法陷阱(转自51CTO)

    1. 哈希对象中key的顺序 比如,你要存储一个简单的文字对象:: > db.books.insert({ title: "Woe from Wit", meta: { au ...

  7. 【Java 系列笔记】语法基础 + Spring + Spring MVC + SpringBoot + 数据结构

    Java 强化笔记目录 Java 语言基础 Java 架构师体系课程 一些课程 前端笔记:前端学习笔记 Java 语言基础 回头补基础(此基础非小白)系列,学校教的其实真的就是一些皮毛而已,怕是连门都 ...

  8. hsqldb mysql 语法_[spring batch]建表语句(hsqldb改mysql)

    /** * @see https://spring.io/guides/gs/batch-processing/ */ @Configuration @EnableBatchProcessing pu ...

  9. python操作mongodb语法_python操作mongodb怎么找到所有的集合

    {"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],&q ...

最新文章

  1. nyoj 762:第k个互质数
  2. 设置ALV单元格可编辑状态
  3. [js高手之路]从原型链开始图解继承到组合继承的产生
  4. webServlet(/) 和 webServlet(/*) 的区别
  5. pascal voc数据集_【资源分享】数据集搜索神器BIFROST
  6. 百分之六的谷歌云存储桶因配置错误而遭任意访问
  7. 51单片机波特率计算c语言,51单片机波特率怎么算?51单片机波特率计算公式
  8. Power Query 系列 (05) - M 语言介绍
  9. 傅里叶级数与傅里叶变换_Part1_三角函数系的正交性
  10. Excel:列的顺序颠倒(d-a列变成a-d列)
  11. HMI——“已连续登录3次,用户已注销”问题
  12. 网页配色网页设计常用色彩搭配表 《配色表》
  13. 删除ttf字体文件中无用文字
  14. 你还不知道钉钉服务端API全局错误码吗?
  15. 2021年中国货物进出口规模及呈现的五大特点分析:货物进出口快速增长,贸易结构持续优化[图]
  16. JVM(4)—类加载机制
  17. 局域网git服务器搭建(基于win7 + bonobo git server)
  18. Wildfly 10的安装、配置到部署
  19. Html5的废弃与新增全局属性及元素
  20. 南网电费接口API文档分享

热门文章

  1. mac 雪豹 10.6 五国
  2. Less 命令技巧,从底部网上看
  3. 饿了么CTO张雪峰:允许90后的技术人员“浮躁“一点
  4. SQL基础整理——例题
  5. jQuery实现的简单分页功能的详细解析
  6. 安卓开源项目周报1220
  7. Easyui主要组件用法
  8. cp 提示 overwrite 问题
  9. wpf资源嵌套,一个资源引用另外一个资源,被引用的资源应该声明在前面
  10. Mariadb的安装与配置