日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

mongodb语法与spring实现

發布時間:2024/4/13 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mongodb语法与spring实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

mongodb語法

參考文檔:https://docs.mongodb.com/manual/reference/

BSON Types

BSON Type有2種標識符,整形和字符串

類型數值字符串說明
Double1“double”
String2“string”
Object3“object”
Array4“array”
Binary data5“binData”
Undefined6“undefined”Deprecated.
ObjectId7“objectId”
Boolean8“bool”
Date9“date”
Null10“null”
Regular Expression11“regex”
DBPointer12“dbPointer”Deprecated.
JavaScript13“javascript”
Symbol14“symbol”Deprecated.
JavaScript (with scope)15“javascriptWithScope”
32-bit integer16“int”
Timestamp17“timestamp”
64-bit integer18“long”
Decimal12819“decimal”New in version 3.4.
Min key-1“minKey”
Max key127“maxKey”

可以使用***$type***操作符使用這些類型。

BSON特定類型

ObjectId

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

String

UTF-8格式,

Timestamps

Date

64位整形,從1970.01.01開始的毫秒數。

查詢和投影操作符

Name意義
比較操作符
$eq相等
$gt大于
$gte大于等于
$in包含在集合中
$lt小于
$lte小于等于
$ne不等于
$nin不在集合中
邏輯操作符
$andAND
$notNOT
$nor同時滿足2個條件的,則為false
$orOR
元素操作符
$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,排序數組
位運算
$bitPerforms bitwise AND, OR, and XOR updates of integer values.

聚合管道階段

MongoDB的聚合管道將MongoDB文檔在一個管道處理完畢后將結果傳遞給下一個管道處理。管道操作是可以重復的。
表達式:處理輸入文檔并輸出。表達式是無狀態的,只能用于計算當前聚合管道的文檔,不能處理其它的文檔。

集合聚合

db.collection.aggregate()

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

StageDescription示例
$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修改輸入文檔的結構??梢杂脕碇孛⒃黾踊騽h除域,也可以用于創建計算結果以及嵌套文檔。$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

聚合管道操作(標量函數)

NameDescription示例
數學計算
$abs求絕對值
$add加法
$ceil大于等于指定值的最小整數
$divide除法
$exp指數
$floor小于等于指定值的最大整數
$ln自然對數
$log對數
$log1010為底對數
$mod求模
$multiply乘法
$pow求冪
$roundround
$sqrt求二次根
$subtract減法
$trunc截斷
數組操作
$arrayElemAt求index
$arrayToObject數組轉document
$concatArrays連接數組
$filter過濾
$in在集合中
$indexOfArray第一個匹配的index
$isArray是否數組
$mapmap
$objectToArray對象轉數組
$range
$reduce
$reverseArray
$size數組大小
$slice數組切片
$zip合并2個數組
邏輯表達式
$andand
$notnot
$oror
比較操作符
$cmp*比較**2**個操作數*
$eq相等
$gt大于
$gte大于等于
$lt小于
$lte小于等于指定值的最大整數
$ne不等
條件操作符
NameDescription
$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
類型操作
$convertConverts a value to a specified type.(since4.0)
$toBoolConverts value to a boolean.(since4.0)
$toDateConverts value to a Date.(since4.0)
$toDecimalConverts value to a Decimal128.(since4.0)
$toDoubleConverts value to a double.(since4.0)
$toIntConverts value to an integer.(since4.0)
$toLongConverts value to a long.(since4.0)
$toObjectIdConverts value to an ObjectId.(since4.0)
$toStringConverts value to a string.(since4.0)
$typeReturn 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); 超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的mongodb语法与spring实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。