【问题标题】:Add sum of order from order collection to user collection in mongoose将订单集合中的订单总和添加到猫鼬中的用户集合
【发布时间】:2021-12-04 08:11:01
【问题描述】:

我目前正在做一个 nodejs 项目,我正在使用 mongodb 作为我的数据库,但我遇到了一个问题。我想使用聚合进行一次调用,将特定用户订单的总和添加到用户集合中。但我不知道该怎么做。请我需要一些关于如何实现这一目标的建议/帮助。请参阅下面的对象示例。

用户收藏

[
  {
    _id: 1,
    name: "Henry"
  },
  {
    _id: 2,
    name: "John"
  }
]

订单收集

[
  {
    _id: 1,
    userId: 2
  },
  {
    _id: 2,
    userId: 2
  },
  {
    _id: 3,
    userId: 1
  }
]

拨打猫鼬电话后的预期结果

[
  {
    _id: 1,
    name: "Henry",
    orderCount: 1
  },
  {
    _id: 2,
    name: "John",
    orderCount: 2
  }
]

【问题讨论】:

标签: node.js mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

查询

  • 按 userId 对订单进行分组并对 orderCount 求和
  • 查询用户获取用户信息(此处为name字段)

Test code

orders.aggregate(
[{"$group": {"_id": "$userId", "orderCount": {"$sum": 1}}},
  {"$lookup": 
    {"from": "users",
     "localField": "_id",
     "foreignField": "_id",
     "as": "users"}},
  {"$set": {"name": {"$arrayElemAt": ["$users.name", 0]}}},
  {"$unset": ["users"]}])

如果您的用户有更多字段,而不仅仅是 name,请替换 $set 有了这个

{"$replaceRoot": 
  {"newRoot": {"$mergeObjects": ["$$ROOT" , {"$arrayElemAt": ["$users", 0]}]}}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2021-01-18
    • 2022-08-08
    相关资源
    最近更新 更多