根据您提供的MongoDB服务器版本:
你要么实现使用$indexOfArray
用MongoDB的3.4为最短的方式做到这一点:
db.getCollection('collection').aggregate([
{ "$addFields": {
"orderitems": {
"$map": {
"input": "$orderitems",
"as": "o",
"in": {
"description": "$$o.description",
"proposals": {
"$arrayElemAt": [
"$$o.proposals",
{ "$indexOfArray": [
"$$o.proposals.value",
{ "$min": "$$o.proposals.value" }
]}
]
}
}
}
}
}}
])
或用MongoDB的3.2就可以$filter
和拿第一个配对元素$arrayElemAt
:
db.getCollection('collection').aggregate([
{ "$addFields": {
"orderitems": {
"$map": {
"input": "$orderitems",
"as": "o",
"in": {
"description": "$$o.description",
"proposals": {
"$arrayElemAt": [
{ "$filter": {
"input": "$$o.proposals",
"cond": { "$eq": ["$$this.value",{ "$min": "$$o.proposals.value" }] }
}},
0
]
}
}
}
}
}}
])
在任何低于这个版本的版本中尝试和实现它都会很痛苦。
基本原理是根据$min
返回的值进行匹配,它在MongoDB 3.2中得到了一些改变,因此它可以用来从任何数组值中返回“最小”值,而不仅仅是作为“累加器”在聚集$group
改为3.2版本:$分钟是在$组和$项目阶段提供。在之前的MongoDB版本中,$ min仅在$ group阶段可用。
所以一般的情况下是由我们无论是从$indexOfArray
匹配索引或返回值的任何被返回作为匹配的$filter
阵列条目的阵列条目相匹配。
根据所选的方法,'匹配索引'被送入$arrayElemAt
以提取该索引处的数组值,或使用0
索引从“过滤列表”中获取“第一个”元素。
两种方法都返回:
{
"requester" : "test",
"orderitems" : [
{
"description" : "testitem1",
"proposals" : {
"company" : "company2",
"value" : 5.0
}
}
]
}