Home > Enterprise >  push an array element if certain element not exists or update in mongodb
push an array element if certain element not exists or update in mongodb

Time:04-16

I have to update an array inside a document on the basis of a string which i get from the req.value.

My collection

[
  {
    "_id": 1,
    "key": [
      "1-value-1",
      "1-value-2"
    ]
  },
  {
    "_id": 2,
    "key": [
      "2-value-1",
      "2-value-2"
    ]
  }
]

I have another string newString. Let's assume two conditions:

  • when req.value is in the array in that case replace the array value with newString.
  • else rew.value is not present simple push the newString in the array.

Eg: I have a newString = 1-value-3 and req.value = 1-value-2 in that case replace array value 1-value-2 to 1-value-3. Else if req.value isn't in array push newString value to array.

This is the collection on which i want to perform operations on.

Thanks for answering in advance.

CodePudding user response:

Update with pipeline

Query

  • if 1-value-2 exists change to 1-value-3
  • else `push 1-value-3 in the end of the array (i think you want this)
  • filter to check if it exists
  • if exists map to update
  • else concat to add in the end of the array

Playmongo(update,exists)
Playmongo(push(concat), missing)

update(
{"_id": {"$eq": 1}},
[{"$set": 
   {"v2-exists": 
     {"$ne": 
       [{"$filter": 
           {"input": "$key", "cond": {"$eq": ["$$this", "1-value-2"]}}},
         []]}}},
 {"$set": 
   {"key": 
     {"$cond": 
       ["$v2-exists",
         {"$map": 
           {"input": "$key",
            "in": 
             {"$cond": 
               [{"$eq": ["$$this", "1-value-2"]}, "1-value-3", "$$this"]}}},
         {"$concatArrays": ["$key", ["1-value-3"]]}]}}},
 {"$unset": ["v2-exists"]}])

Update operators

Query1(check if exists)

find({"_id": {"$eq": 1}, "key": {"$elemMatch": {"$eq": "1-value-2"}}})

If query1 empty result send this(push at the end)

update(
{"_id": {"$eq": 1}},
{"$push": {"key": "1-value3"}})

else send this (set to replace the old value)

update(
{"_id": {"$eq": 1}},
{"$set": {"key.$[m]": "1-value-3"}},
{"arrayFilters": [{"m": {"$eq": "1-value-2"}}]})
  • Related