首页 > 解决方案 > 根据 MongoDB 中此数组中的条件元素编号推送数组中的元素

问题描述

假设我有这个集合things

db={
  "things": [
    {
      _id: 1,
      users: [
        {
          userId: 1,
          role: "creator"
        },{
          userId: 2,
          role: "spectator"
        },{
          userId: 3,
          role: "left"
        }
      ],
      nbMax:2
    },
    {
      _id: 2,
      users: [
        {
          userId: 2,
          role: "creator"
        },{
          userId: 1,
          role: "spectator"
        },{
          userId: 3,
          role: "left"
        }
      ],
      nbMax:3
    }
  ]
}

我想在具有以下条件users的给定字段中推送一个新用户_id:具有角色的用户数creator必须spectator低于该字段nbMax

在这个例子中:

推送一个新用户_id: 1 不起作用,因为nbMax= 2 并且已经有 1 个创建者和 1 个观众(left不计算在内)

为 : 2 推送一个新用户是_id有效的,因为nbMax= 3 并且已经只有 1 个创建者和 1 个观众。

有没有办法使用 mongodb 执行该操作,或者我应该将此查询拆分为 nodejs 中的 2 个查询,例如:_ 检查用户大小和nbMax _ 如果可以:推送一个新用户

我已经尝试使用查询,update但到目前为止没有任何效果,我想知道我想做的是否是一个好的 mongodb 实践。aggregate$size

编辑:我创建了一个给定 _id的aggregate用户数:creatorspectator

db.things.aggregate([
  {
    "$match": {
      _id: 1
    }
  },
  {
    "$unwind": "$users"
  },
  {
    "$match": {
      "users.role": {
        $in: [
          "creator",
          "spectator"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": 1,
      "count": {
        "$sum": 1
      }
    }
  }
])

这是一个演示

标签: node.jsmongodbaggregation-framework

解决方案


推荐阅读