英文:
How to get sum of values in array of objects in mongodb
问题
从具有金额和金额日期的对象数组中使用某些操作获取当天的总支出。
英文:
i have a mongodb recor which looks like this .
[
{
"_id": {
"$oid": "64a5a396ec152ab4f5e1c60c"
},
"firstName": "Ram",
"lastName": "Shayam",
"email": "abc@123.com",
"transactions": [
{
"amount": 22,
"date": "21/7"
},
{
"amount": 12,
"date": "21/7"
},
{
"amount": 50,
"date": "19/7"
},
{
"amount": 100,
"date": "19/7"
}
]
}
]
now i gave to filter transactions on the basis of date by doing these operations:
db.collection.aggregate([
{
$match: {
firstName: "Ram"
}
},
{
$unwind: "$transactions"
},
{
$match: {
"transactions.date": {
$eq: "21/7"
}
}
},
{
$group: {
_id: "$_id",
list: {
$push: "$transactions"
}
}
}
])
and getting shorted array with transactions of only given dates like this...
[
{
"_id": ObjectId("64a5a396ec152ab4f5e1c60c"),
"list": [
{
"amount": 22,
"date": "21/7"
},
{
"amount": 12,
"date": "21/7"
}
]
}
]
**now how to get the total amount spend on that day using some other operations.
like i want to get 34 as output by doing operations.
here is the playground link for more details.**
how to get the total amount spend on that day using some operations from a array of objects with amount and date of amount.
答案1
得分: 4
db.collection.aggregate([
{
$match: {
firstName: "Ram"
}
},
{
$unwind: "$transactions"
},
{
$match: {
"transactions.date": {
$eq: "21/7"
}
}
},
{
$group: {
_id: "$_id",
list: {
$push: "$transactions"
},
total: {
$sum: "$transactions.amount"
}
}
}
])
英文:
db.collection.aggregate([
{
$match: {
firstName: "Ram"
}
},
{
$unwind: "$transactions"
},
{
$match: {
"transactions.date": {
$eq: "21/7"
}
}
},
{
$group: {
_id: "$_id",
list: {
$push: "$transactions"
},
total: {
$sum: "$transactions.amount"
}
}
}
])
答案2
得分: 1
添加了**$sum**来计算
db.collection.aggregate([
{
$match: {
firstName: "Ram"
}
},
{
$unwind: "$transactions"
},
{
$match: {
"transactions.date": {
$eq: "21/7"
}
}
},
{
$group: {
_id: "$_id",
list: {
$push: "$transactions"
},
count: {
$sum: "$transactions.amount"
}
}
}
])
英文:
added $sum to count
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
db.collection.aggregate([
{
$match: {
firstName: "Ram"
}
},
{
$unwind: "$transactions"
},
{
$match: {
"transactions.date": {
$eq: "21/7"
}
}
},
{
$group: {
_id: "$_id",
list: {
$push: "$transactions"
},
count: {
$sum: "$transactions.amount"
}
}
}
])
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论