mongodb语法与spring实现

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开始的毫秒数。

 

查询和投影操作符

Query Selectors
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,$addToSet,循环数组中的每个元素当做一个对象,而不是整个数组作为一个对象  
$position 修饰$push,指定插入位置  
$slice 修饰$push,限制修改数组的大小  
$sort 修饰$push,排序数组  
 
位运算
$bit Performs bitwise ANDOR, and XOR updates of integer values.  

聚合管道阶段

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

集合聚合

db.collection.aggregate()

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

Stage Description 示例
$addFields 增加新字段到文档中,类似$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: "$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( [ {  }, ... ] )

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: "井场调查基本数据表",
                    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: "油气资源详探",
        ru: null,
        pt: "井场调查基本数据表",
        bw: "基础研究",
        bot: "井",
        root: null,
        createdate: null,
        publisher: null,
        title: "井场调查基本数据表",
        bo: "",
        bp: "井场调查",
        ds: "钻井"
    },
    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 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 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 valuesAll = (List) 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 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)