Xameer
Xameer

Reputation: 31237

How to compare object in mongodb update query

We've a MongoDB collection like this:

[
  {
    "field1": {
      "key1": true,
      "key2": false
    }
  },
  {
    "field1": {
      "key1": true,
      "key2": true
    }
  }
  ...
  ...
]

which we need to update with a condition on field1 which is an object.

We have used a query like this:

document.update({
    { field1: { key1: false, key2: true } }
  }, {
    $set: required updates
  }, {
    multi: true
  })
  .then(() => {})
  .catch((err) => {});

however it doesn't seems to be having an effect.

How do we fix this?

Upvotes: 1

Views: 88

Answers (2)

Ashh
Ashh

Reputation: 46441

You need to use .Dot notation for the fields inside object

document.update(
  { "field1.key1": false, "field1.key2": true },
  { "$set": required updates },
  { "multi": true }
)

Upvotes: 1

Harshal Yeole
Harshal Yeole

Reputation: 4983

Try this code:

document.update(
    {
        $and: [{ "field1.key1": false }, { "field1.key2": true }]
    },
    {
        $set:  required updates  // It (required updates) should be an object
    },
    {
        multi: true
    })
    .then(() => { })
    .catch((err) => { });

Hope it gives you an idea!!

Upvotes: 1

Related Questions