我收集了檔案,例如:
[
{
'id':'1'
'some_field':'test',
'rates':[
{'user_id':'12','rate':'very_good'},
{'user_id':'13','rate':'very_good'}
{'user_id':'14','rate':'bad'},
{'user_id':'15','rate':'normal'}
]
}
]
我收集了字串中的費率值:
[
{
"rate_name" : "bad",
"rate_value" : 1
},
{
"rate_name" : "normal",
"rate_value" : 2
},
{
"rate_name" : "very_good",
"rate_value" : 3
},
]
我需要將來自陣列速率的第一個集合中的資料與來自第二個集合的值進行映射,并將這些值分組到新欄位。
例如:
[
{
'id':'1'
'some_field':'test',
'rates':[3,3,1,2]
]
}
]
我怎么能這樣做?
uj5u.com熱心網友回復:
如果"$getField"可用,這是您可以做到的一種方法(MongoDB 服務器版本 5.0 及更高版本)。請參閱下面的另一種選擇。
db.ratings.aggregate([
{
"$lookup": {
"from": "ratingScale",
"as": "ratingScale",
"pipeline": []
}
},
{
"$set": {
"rates": {
"$map": {
"input": "$rates",
"as": "rate",
"in": {
"$getField": {
"field": "rate_value",
"input": {
"$first": {
"$filter": {
"input": "$ratingScale",
"as": "nameValue",
"cond": {"$eq": ["$$rate.rate", "$$nameValue.rate_name"]}
}
}
}
}
}
}
}
}
},
{"$unset": "ratingScale"}
])
在mongoplayground.net上試試。
如果"$getField"不可用,這是另一種方法。
db.ratings.aggregate([
{
"$lookup": {
"from": "ratingScale",
"as": "ratingScale",
"pipeline": []
}
},
{
"$set": {
"rates": {
"$map": {
"input": "$rates",
"as": "rate",
"in": {
"$first": {
"$filter": {
"input": "$ratingScale",
"as": "nameValue",
"cond": {"$eq": ["$$rate.rate", "$$nameValue.rate_name"]}
}
}
}
}
}
}
},
{
"$set": {
"rates": {
"$map": {
"input": "$rates",
"as": "rate",
"in": "$$rate.rate_value"
}
}
}
},
{"$unset": "ratingScale"}
])
在mongoplayground.net上試試。
uj5u.com熱心網友回復:
你可以做一個簡單的$unwind然后$lookup方法。
db.col1.aggregate([
{
$unwind: "$rates"
},
{
"$lookup": {
"from": "col2",
"localField": "rates.rate",
"foreignField": "rate_name",
"as": "rates"
}
},
{
"$unwind": "$rates"
},
{
$group: {
_id: "$_id",
some_field: {
$first: "$some_field"
},
rates: {
$push: "$rates.rate_value"
}
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522642.html
