Mongodb. How to use elemMatch as condition to update fields

  Kiến thức lập trình

I have two array of objects i my documents.

{
  "profileSpherestatus": [
    {
      "idf": "B002",
      "completedPercentage": 100
    },
    {
      "idf": "B003",
      "completedPercentage": 90
    },
    {
      "idf": "B004",
      "completedPercentage": 100
    }
  ]
  "myGratificacions": [
    {
      "idb": "B003",
      "gratification": 20
    },
    {
      "idb": "B004",
      "gratification": 30
    }
  ]
}

I want to add a new object in myGratifications if there is at least one object in the profileSpherestatus array where idf is “B002” and completedPercentage is 100, and there is not a gratification with “idb”:”B002″

The newobject is:

newObject = {
  "idb":"B002",
  "gratification":10
}

This is my pipeline:

[
  {"$set": {
    "myGratifications":
      {"$cond": {
        "if": {
          "$and": [
            {"profileSpherestatus": 
              {"$elemMatch": {"idf": "B002", "completedPercentage": 100}}
            },
            {"$not": 
              {"myGratifications":{"$elemMatch": {"idb": "B002"}}}
            }
          ]
        },
        "then": {
            "$concatArrays": ["$myGratifications",[newObject]]
        },
        "else": "$myGratifications"
    }}
  }} 
]

But $elemMatch cannot be used inside $set or $addFields. Can you help me?

LEAVE A COMMENT