我有对象数组(嵌套),我想从这些嵌套对象中提取几个元素,并在数组中返回这些字段。下面是我的文档结构(从原始数据中嘲笑)
"detailLine": [
{
"name": "first",
"value": {
"lineNumber": 1,
"subLineCode": " ",
"detailLineCharges": {
"allowedAmount": {
"amount": "11111",
"reasonCode": “aaaah”
}
}
}
},
{
"name": "first",
"value": {
"detailLineCharges": {
"allowedAmount": {
"amount": "22222",
"reasonCode": “BBBB”
}
}
}
}
]
我希望看到我的结果
details: [
{
amount:”11111”,
reasonCode : “aaaah”
},
{
amount : “22222”,
reasonCode : “BBBB”
}
]
我试过
db.collection.aggregate([
{
$match: {
_id: "123456"
}
},
{
$project: {
details: {
$push {
amount: "$detailLine.value.detailLineCharges.allowedAmount.amount",
reasoncode: "$detailLine.value.detailLineCharges.allowedAmount.reasonCode"
}
}
}
}
])
但我收到此错误
Error: command failed: { "ok" : 0, "errmsg" : "invalid operator '$push'", "code" : 15999 } : aggregate failed :
我想使用$project
,因为我使用它来提取太多其他字段,这就是为什么我没有尝试$group
这个特定情况。
任何人都可以帮助如何在数组中获取这两个字段吗?
答案 0 :(得分:5)
嗯,您需要的只是$project
您的文档,并使用$map
运算符“重塑”它们。
db.coll.aggregate(
[
{ "$match": { "_id": "123456" } },
{ "$project": {
"detailLine": {
"$map": {
"input": "$detailLine",
"as": "dline",
"in": {
"amount": "$$dline.value.detailLineCharges.allowedAmount.amount",
"reasonCode": "$$dline.value.detailLineCharges.allowedAmount.reasonCode"
}
}
}
}}
]
)
答案 1 :(得分:2)
使用以下管道,虽然我使用given
,但它会为您提供所需的结果。当然,您可能需要调整组标识符。
|scenario | myDivision _ _ _|numerator, denominator, quotient|
|setNumerator | @numerator |
|setDenominator | @denominator|
|check | quotient| @quotient |
| myDivision | having |numerator| 12|
| denominator|quotient|
| 3 |4.0 |
| 6 |2.0 |
| 4 |3.0 |
结果
$group
答案 2 :(得分:-1)
您忘记在$ push中添加冒号
\n\n
更改为
$project: {
details: {
$push {
amount: "$detailLine.value.detailLineCharges.allowedAmount.amount",
reasoncode: "$detailLine.value.detailLineCharges.allowedAmount.reasonCode"
}
}
}