'Mongodb aggregate group by then conditional sum, or, filter, push, using c#
Can someone please help to convert this query to C# .NET core?
db.getCollection("accout").aggregate().match({ $or: [{"clientnum1": "xxxx"},{ "clientnum2": ""}], "accNo":"00001","currCd":"INR"} ).sort({mktValueBased:-1}).group({_id: "$catName",holdings:{$push: {name: "$secName",currCd: "$currCd",currCdBased: {$cond: [{$in: ["$serviceType", ["a","b","c"]]}, "$Cd", "$Cd"]},cost : "$cost",costBased : {$cond: [{$in: ["$serviceType", ["a","b","c"]]}, "$AccBased", "$costBased"]},mktVal: "$mktValue",mktValBased: {$cond: [{$in: ["$serviceType", ["a","b","c"]]}, "$mktAccBased", "$mktValueBased"]},uPL: round({ $subtract: ["$mktValue","$cost"] }, 2),uPLPct: round({$cond: [{$eq: ["$cost",0]}, 0, { $multiply: [{ $divide: [{ $subtract: ["$mktValue","$cost"] }, {$cond: [{$gt: ["$cost",0] },"$cost",1]} ]}, 100] }]},2)}}}).sort( { _id: 1, data: 1 } ).group({ _id: null, data: {$push: {groupName: "$_id",holdings: "$holdings"}}}).project( { _id: 0, data: 1 }})
`
db.collection.aggregate([
{
"$match": {
$or: [ { "clientnum1": "xxxx" }, { "clientnum2": "" } ],
"accNo": "00001",
"currCd": "INR"
}
},
{
"$sort": { mktValueBased: -1 }
},
{
"$group": {
_id: "$catName",
holdings: {
$push: {
name: "$secName",
currCd: "$currCd",
currCdBased: {
$cond: [
{ $in: [ "$serviceType", [ "a", "b", "c" ] ] },
"$Cd",
"$Cd"
]
},
cost: "$cost",
costBased: {
$cond: [
{ $in: [ "$serviceType", [ "a", "b", "c" ] ] },
"$AccBased",
"$costBased"
]
},
mktVal: "$mktValue",
mktValBased: {
$cond: [
{ $in: [ "$serviceType", [ "a", "b", "c" ] ] },
"$mktAccBased",
"$mktValueBased"
]
},
uPL: { $round: [ { $subtract: [ "$mktValue", "$cost" ] }, 2 ] },
uPLPct: {
$round: [
{
$cond: [
{ $eq: [ "$cost", 0 ] },
0,
{
$multiply: [
{
$divide: [
{ $subtract: [ "$mktValue", "$cost" ] },
{ $cond: [ { $gt: [ "$cost", 0 ] }, "$cost", 1 ] }
]
},
100
]
}
]
},
2
]
}
}
}
}
},
{
"$sort": { _id: 1, data: 1 }
},
{
"$group": {
_id: null,
data: { $push: { groupName: "$_id", holdings: "$holdings" } }
}
},
{
"$project": { _id: 0, data: 1 }
}
])
Solution 1:[1]
you can use Studio 3T plugin to convert it into c# code.
Note: Studio 3T is a licensed product but you can use there 30-day free trial
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JM007 |