Home > Software design >  How to use two operators in one query with arrayFilters condition in MongoDB / Node.js?
How to use two operators in one query with arrayFilters condition in MongoDB / Node.js?

Time:01-17

I'm trying to update the cash field (increment) and the active field (from true to false) that is in a nested document. I'm using node.js and mongodb.

I have this document:

[
  {
    "name": "Josh",
    "personId": "1234",
    "cash": 100,
    "events": [ {"type": "event1", "active": true }, {"type": "event2", "active": true}]
  },
  {
    "name": "Angelo",
    "personId": "7890",
    "cash": 50,
    "events": [ {"type": "event1", "active": true }, {"type": "event2", "active": true}]
  }
]

Here's my query

db.collection("users").updateOne({ personId: personId }, { $inc: { cash: 100 }, $set: {"events.$[elem].active": false }, arrayFilters: [{ "elem.type": "event1" }] })

But I'm getting "Uncaught MongoServerError MongoServerError: No array filter found for identifier 'elem' in path 'events.$[elem].status". Might have something to do with my syntax.

I can update the nested field "active" just fine with this without the increment:

db.collection("users").updateOne({ personId: personId}, { $set: {"events.$[elem].active": false }}, {arrayFilters: [{ "elem.type": "event1" }] })

How do I use $inc and $set with an arrayFilters condition (arrayFilters is for the $set only)?

CodePudding user response:

Your syntax is wrong. Check the docs where it says:

db.collection.updateMany(
   { <query conditions> },
   { <update operator>: { "<array>.$[<identifier>]" : value } },
   { arrayFilters: [ { <identifier>: <condition> } ] }
)

You can see there are three objects: query, update and arrayFilters. And you only have two.

So you can use:

db.collection.update({
  personId: "1234"
},
{
  $inc: {
    cash: 100
  },
  $set: {
    "events.$[elem].active": false
  },
  
},
{
  arrayFilters: [
    {
      "elem.type": "event1"
    }
  ]
})

Example here

  • Related