[英]Project embedded document key value, based on condition in mongoDB aggregation
我有一個稱為票證的mongo集合,我們將票證詳細信息存儲在類似的結構文檔中,如下所示:
[
{
"status": "PAUSED",
"lifecycle_dates": {
"OPEN": "d1",
"CLOSED": "d2",
"PAUSED": "d3"
}
},
{
"status": "OPEN",
"lifecycle_dates": {
"OPEN": "d1",
"PAUSED": "d3"
}
},
{
"status": "CLOSED",
"lifecycle_dates": {
"OPEN": "d1",
"CLOSED": "d2"
}
}
]
我需要獲取表示票證當前狀態和日期的日期的數據。
我想像這樣投射數據:
[
{
"status": "PAUSED",
"lifecycle_date": "d3"
},
{
"status": "OPEN",
"lifecycle_date": "d1"
},
{
"status": "CLOSED",
"lifecycle_date": "d2"
}
]
如何根據mongo聚合管道中的當前狀態預測單個生命周期日期? 像這樣的東西:
{
$project : {
"status" : 1,
"lifecycle_date" : $lifecycle_dates[$status]
}
}
在這里的mongo參考文檔中找不到任何參考或類似問題
當前的mongo版本:3.2
更新的答案:
因為你需要獲取date
為每status
,您可以使用此匯總查詢:
db.test.aggregate([
{
$project : {
_id : 0,
status : 1,
lifecycle_date : { $cond: [ {$eq : ["$status","OPEN"]}, "$lifecycle_dates.OPEN", { $cond: [ {$eq : ["$status","CLOSED"]}, "$lifecycle_dates.CLOSED", { $cond: [ {$eq : ["$status","PAUSED"]}, "$lifecycle_dates.PAUSED", "-1" ]} ]} ]}
}
}])
這也與Mongo 3.2兼容。
輸出:
{ "status" : "PAUSED", "lifecycle_date" : "d3" }
{ "status" : "OPEN", "lifecycle_date" : "d1" }
{ "status" : "CLOSED", "lifecycle_date" : "d2" }
================================================== =======================
這個答案是針對上一個問題的-
使用此聚合:
db.test.aggregate([
{
$project : {
_id : 0,
status : 1,
lifecycle_date : "$lifecycle_dates.PAUSED"
}
}
])
輸出:
{ "status" : "PAUSED", "lifecycle_date" : "d3" }
您可以嘗試以下匯總
db.collection.aggregate([
{ "$project": {
"status": 1,
"lifecycle_date": {
"$arrayElemAt": [
{ "$filter": {
"input": { "$objectToArray": "$lifecycle_dates" },
"as": "life",
"cond": { "$eq": ["$$life.k", "$status"] }
}},
0
]
}
}},
{ "$project": {
"status": 1,
"lifecycle_date": "$lifecycle_date.v"
}}
])
db.tickets.aggregate(
// Pipeline
[
// Stage 1
{
$project: {
"status": 1,
_id: 0,
"lifecycle_dates": {
$switch: {
branches: [{
case: {
$eq: ["$status", "PAUSED"]
},
then: "$lifecycle_dates.PAUSED"
},
{
case: {
$eq: ["$status", "OPEN"]
},
then: "$lifecycle_dates.OPEN"
},
{
case: {
$eq: ["$status", "CLOSED"]
},
then: "$lifecycle_dates.OPEN"
}
],
}
}
}
},
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.