表示存在于mongoDB聚合中数组内部某个位置的对象 [英] Represent object present at a position inside an array in mongoDB aggregation
问题描述
在聚合中,我试图投影position 7 inside an array
中存在的object(which is an array)
.例如,我有以下字段
In aggregation i am trying to project an object(which is an array)
which is present at position 7 inside an array
. For example i have fields as below
{
"$project": {
"result": {
"$cond": {
"if": {
"$eq": ["$coupon_type", 1]
},
"then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"],
"else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", {
indexes: conditions
}]
}
}
}
},
{
"$project": {
obj: { $arrayElemAt: [ "$result", 7 ] } // here how to project indexes.
}
所以对于coupon_type: 0
,现在我将结果投影为["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { indexes: conditions}]
.
So now for coupon_type: 0
i will project my result as ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { indexes: conditions}]
.
现在我要在下一个管道中投影的字段是索引",所以我尝试编写$arrayElemAt: [ "$result", 7 ]
,这给了我第七个索引元素,这是正确的,但是我应该如何表示在此第七个位置存在的对象索引" .
Now the field i want to project in my next pipeline is 'indexes' so i tried to write $arrayElemAt: [ "$result", 7 ]
which is giving me 7th index element which is right but how should i represent object 'indexes' present at this 7th position.
简而言之,我想写这样的东西$arrayElemAt: [ "$result", 7 ].indexes
,这不是指向对象的正确方法.
In short i want to write something like this $arrayElemAt: [ "$result", 7 ].indexes
which is not the right way to point to an abject.
任何人都可以告诉我我该怎么做.
Can anyone please tell me how can i do this.
推荐答案
您可以组合项目阶段并使用$let
来投影索引.
You can combine the project stages and use $let
to project the index.
$project: {
indexes: {
$let: {
vars: {
obj: {
$arrayElemAt: [{
"$cond": {
"if": {
"$eq": ["$coupon_type", 1]
},
"then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"],
"else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", {
indexes: conditions
}]
}
}, 7]
}
},
in: "$$obj.indexes"
}
}
}
这篇关于表示存在于mongoDB聚合中数组内部某个位置的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!