MongoDb使用$add聚合嵌套文档
我需要从嵌套文档中获取总和值 DB文件:MongoDb使用$add聚合嵌套文档,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我需要从嵌套文档中获取总和值 DB文件: { "_id": 123, "products": [ { "productId": 1, "charges": [ { "type": "che", "amount": 100 } ] } ] } 我想得到和值。 sumValue=产品。费用。金额+20;其中products.productId为1,products
{
"_id": 123,
"products": [
{
"productId": 1,
"charges": [
{
"type": "che",
"amount": 100
}
]
}
]
}
我想得到和值。
sumValue=产品。费用。金额+20;其中products.productId为1,products.charges.type为che
我尝试了以下问题,但没有希望:
db.getCollection('test').aggregate(
[
{"$match":{$and:[{"products.productId": 14117426}, {"products.charges.type":"che"}]},
{ $project: { "_id":0, total: { $add: [ "$products.charges.price", 20 ] } }}
]
)
请帮我解决这个问题。您可以运行两次将数组转换为标量值。外部条件可以应用为,内部条件可以运行为:
可以运行两次将数组转换为标量值。外部条件可以应用为,内部条件可以运行为:
您必须看一看运算符,它解构一个数组,为数组的每个元素输出一个文档。另外,还可以查看和运算符 我假设您的db查询应该如下所示:
您必须看一看运算符,它解构一个数组,为数组的每个元素输出一个文档。另外,还可以查看和运算符 我假设您的db查询应该如下所示:
是否有任何方法可以使用相同的查询更新数据库中的结果?比如使用$Out或$merge aggregator?@phani,如果您使用mongo 4.2,那么这是可能的,但我认为这对于更新数据库比用于生产更方便。看这个:谢谢@thev0id。使用$Merge aggregator,我认为我们不能更新同一个集合。使用$set我们无法保存聚合器结果有没有办法使用相同的查询更新数据库中的结果?比如使用$Out或$merge aggregator?@phani,如果您使用mongo 4.2,那么这是可能的,但我认为这对于更新数据库比用于生产更方便。看这个:谢谢@thev0id。使用$Merge aggregator,我认为我们不能更新同一个集合。使用$set,我们无法保存聚合器结果谢谢您的响应。是否有任何方法可以使用单个查询更新文档中的“总计”值?感谢您的回复。是否有任何方法可以使用单个查询更新文档中的“总计”值?
db.collection.aggregate([
{
"$project": {
_id: 0,
total: {
$reduce: {
input: { $filter: { input: "$products", cond: [ "$$this.productId", 1 ] } },
initialValue: 20,
in: {
$add: [
"$$value",
{
$reduce: {
input: "$$this.charges",
initialValue: 0,
in: {
$cond: [ { $eq: [ "$$this.type", "che" ] }, "$$this.amount", 0 ]
}
}
}
]
}
}
}
}
}
])
db.test.aggregate([
{$unwind: '$products'}, // Unwind products array
{$match: {'products.productId' : 3}}, // Matching product id
{$unwind: '$products.charges'}, // Unwind charges
{$match: {'products.charges.type' : 'che'}}, // Matching charge type of che
{$project: {'with20': {$add: ["$products.charges.amount", 20]}}}, // project total field which is value + 20
{$group: {_id : null, amount: { $sum: '$with20' }}} // total sum
])