Push element in array depending of conditionnal elements number in this array in MongoDB

Viewed 26

Let's say I have this collection of 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
    }
  ]
}

I would like to push a new user in users field for a given _id with this condition : the number of users with role creator and spectator must be lower than the field nbMax

In this example :

Pushing a new user for _id : 1 does not work since nbMax = 2 and there already is 1 creator and 1 spectator (left does not count)

Pushing a new user for _id : 2 works because nbMax = 3 and there already is only 1 creator and 1 spectator.

Is there a way to perform that with mongodb or should I rather split this query in 2 queries in nodejs like : _ checking users size and nbMax _ if it's ok : push a new user

I have tried queries using update, aggregate with $size but nothing works so far, I am wondering if what I want to do is a good mongodb practice.

edit : I have created an aggregate giving me the number of users being creator or spectator for an given _id :

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

This is a demo

0 Answers
Related