html52.com
我爱小程序-开发者交流社区

云数据库聚合(aggregate)时如何操作数组型字段的查询与分组?

{
    "_id":"f885cb355d9ad18d0cc3aed45dc42e87",
    "status":0,
    "items":
        [
            {"pId":"075734515d99df300c4f12df68415e50","pPrice":110.0,"pCost":85.0,"quantity":1.0},
            {"pId":"392890432d99df300c4f12df68415f99","pPrice":110.0,"pCost":85.0,"quantity":2.0}
        ],
    "_openid":"oVCJa5DGovfnzgKr0u2Gn5viMHug"
}


类似于这种典型的数据结构,items为一个对象数组型字段,相当于关系型数据库的子表数据。我业务上需要对items做一些匹配和分组查询。如下语句:

const ordersRes = await db.collection('orders')
    .aggregate()
    .addFields({
      matched: $.in(['$items.pId',pIds])
    })
    .match({
      sellerId: sellerId,
      status: $.neq(-1),
      matched: true
    })
    .group({
      _id: '$items.pId',
      pQuantity: $.sum('$items.quantity')
    })
    .end()


遇到两个问题:

问题1:查询时,想针对pId进行筛选,我事先准好了一个有效的pIds数组,match有效的pId,但输出为0。而我用类似的语法,使用where可以工作,能把匹配上的记录输出。

.where({
      sellerId: sellerId,
      status: _.neq(-1),
      'items.pId': _.in(pIds)
    })


问题2,想针对pId进行分组,合计对应pId的quantity,但是并不能有效分组。实际输出的group条件是一个pId数组,也就是把items下面的多个pId抽取出来组成数组作为group条件了,并不是我所期望的单个pId进行分组,输出结果如下所示:

list: Array(10)
0: {_id: Array(2), pQuantity: 0}
1: {_id: Array(2), pQuantity: 0}
2: {_id: Array(3), pQuantity: 0}
3: {_id: Array(3), pQuantity: 0}
4: {_id: Array(2), pQuantity: 0}
5: {_id: Array(2), pQuantity: 0}
6: {_id: Array(1), pQuantity: 0}
7: {_id: Array(1), pQuantity: 0}
8: {_id: Array(1), pQuantity: 0}
9: {_id: Array(1), pQuantity: 0}


网友回复

快乐的? 单身汉:

还没学到微信云数据库这么高深的知识。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

真正的个人免签约支付接口

云免签H5支付