Compare a string array with object field keys in mongodb

41 Views Asked by At

Assuming that I have the following array a1:

["attr1", "attr2", "attr3"]

and document d1:

{
  "_id": ObjectId("640b0e3629cb7001946137a3")
  "field1": {
        "attr1": { /some data 1},
        "attr2": { /some data 1},
        "attr3": { /some data 1},
        "attr4": { /some data 1},
        "attr5": { /some data 1},
   },
  "field2": {
        "val": "some_val"
   }
}

How can I validate that each value in a1 has a field key in d1.field1 and based on the validation result update d1.field2.val2 in a single update query?

I tried the following query but it's not working:

db.coll.update_one(
        {
            "_id": ObjectId('640b0e3629cb7001946137a3')
        },
        [
            {
                "$set": {
                    "temp_f1": {"$objectToArray": "$fiedl1"}
                }
            },
            {
                "$set": {
                    "field2.val": {"$cond": [{"temp_f1.k": {"$all": a1}}, "UPDATED!", ""]}
                }
            },
            {
                "$unset": "temp_f1"
            },
        ]
    )

I'm new to MongoDB and any help is greatly appreciated.

1

There are 1 best solutions below

2
Noel On

Using $setIsSubset

db.collection.update({},
[
  {
    "$set": {
      "temp_f1": {"$objectToArray": "$field1"}
    }
  },
  {
    "$set": {
      "field2.val": {
        "$cond": [
          {$setIsSubset: [["attr1","attr2","attr3"],"$temp_f1.k"]},
          "UPDATED!",
          ""
        ]
      }
    }
  },
  {
    "$unset": "temp_f1"
  }
],
{
  multi: true
})

Demo