Reputation: 879
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.
}
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}]
.
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.
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.
Upvotes: 1
Views: 292
Reputation: 75934
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"
}
}
}
Upvotes: 1
Reputation: 9285
you can achieve this by adding a second $project stage:
db.collection.aggregate([{
"$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 ] }
},
{"$project": {
obj: "$obj.indexes" }
}
])
Upvotes: 2