[英]MongoDB aggregation with a wildcard in the group
我在MongoDB中收集了一組構建統計信息,我想知道是否可以對其中一個字段進行通配符聚合查詢。
這是一個示例文檔:
{
"_id" : ObjectId("52deab2fe4b0a491abb54108"),
"type" : "build",
"time" : ISODate("2014-01-21T17:15:27.471Z"),
"data" : {
"buildNumber" : 43,
"buildDuration" : 997308,
"buildProjectName" : "Mobile_February",
"branch" : "FEB"
"buildResult" : "SUCCESS"
}
}
我有此查詢,它將按日期和分支提供平均構建持續時間:
db.builds.aggregate([
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfMonth: "$time" },
year: { $year: "$time" },
branch: "$data.branch",
},
buildDuration: { $avg: "$data.buildDuration" }
} },
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1, "_id.branch": 1 } }
])
我們有幾個相同類型的構建作業-每月一個。 有一個Mobile_February,Mobile_March等。對於其他工作,我們也有相同的標准... OtherJob_February,OtherJob_March等。
我想知道的是,是否有某種特定類型的工作更長或更短。 這意味着我不是對分支進行分組,而是對buildProjectName進行分組,但這必須是通配符搜索才能帶回Mobile_ *和OtherJob_ *的分組。
MongoDB有可能嗎? 一種解決方案是添加一個新的元素名稱-類似於“ jobType”:“ Mobile”,但是如果MongoDB可以使用現有數據進行處理,這似乎很浪費。
謝謝!
MongoDB聚合框架具有$ substr-operator ,該操作符返回字符串的固定長度部分。 這有點麻煩,但是您可以根據值的前x個字符進行分組。
db.builds.aggregate([
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfMonth: "$time" },
year: { $year: "$time" },
branch: "$data.branch",
jobType: { $substr: [ "$data.buildProjectName", 0, 6] } // <--
},
buildDuration: { $avg: "$data.buildDuration" }
} },
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1, "_id.branch": 1 } }
])
這將創建兩個附加分組“ JobType”,在這種情況下為“ Mobile”和“ OtherJ”
假設所有作業類型的長度至少為6個字符,則可以使用$ substr運算符提取前6個字符並按該字段分組。 例:
> db.test.aggregate([{$project:{type:{$substr:["$data.buildProjectName", 0, 6]}}}])
{
"result" : [
{
"_id" : ObjectId("52deab2fe4b0a491abb54108"),
"type" : "Mobile"
},
{
"_id" : ObjectId("52deab2fe4b0a491abb54109"),
"type" : "OtherJ"
}
],
"ok" : 1
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.