云开发数据查询问题请教?
发布于 5 年前 作者 hmao 15263 次浏览 来自 问答

数据库结构:

我想查询满足以下条件:

1、查找所有 goods 数组下的_id等于“2a0398605f0ffe5100016fa0427f3c67”的数据

2、把查询到的这些数据的quantity字段值进行总和相加,得到这个总和。

想了很久没有想出来,望得到指导,谢谢!

3 回复
let res = await db.collection('xxx')
        .aggregate()
        .match({
            _id: 'f4.....c7a' //这条数据的_id
        })
        .unwind({
            path: '$goods'
        })
        .addFields({
                        //quantity字段的总和
            quantityTotal: $.sum('$quantity') 
        })
        .match({
                        //goods下面的_id
            'goods._id''2a0398605f0ffe5100016fa0427f3c67'
        })
                .end()
db.collection('test')
.aggregate()
.match({
  _id: 'TmHab2NCFhpVcETxWYPyHWLto8aHiUmduseSalwEU6TqGdWm',
})
.project({
  goods: $.filter({
    input: '$goods',
    as: 'item',
    cond: $.eq(['$$item._id', '2a0398605f0ffe5100016fa0427f3c67'])
  })
})
.unwind('$goods')
.replaceRoot({
   newRoot: '$goods'
})
.group({
  _id: null,
  totalPrice: $.sum('$quantity')
})
.end()
回到顶部