0

I have a model schema like this:

Collection: {
    irrelevant fields,
    object: { 
        more irrelevant fields,
        array:
        [
            {
                field1,
                field2,
                _id: false
            }
        ]
    }
}

I want to push to array any object {field1, field2} that does not repeat with field1 already existing in array (in an updateOne query). field2 is constantly updating itself and i have tried addtoset but it considers field2 so it ends up adding another item i don't want to add.

For example:

array:[
    {field1: 1, field2: 6},
    {field1: 2, field2: 4},
    {field1: 3, field2: 1}
]

if i would want to push {field1: 2, field2: 6} it should not let me push it because the field1:2 already exists in array. (using addtoset, even it does check that the field1:2 already existis, it ends up adding te object because of field2 being different)

array:[
    {field1: 1, field2: 6},
    {field1: 2, field2: 4},
    {field1: 3, field2: 1}
    {field1: 2, field2: 6}
]

1 Answer 1

2

You could use the pipeline form of update with the $cond operator. If the field1 value already exists, keep the value of the array the same, if not, append the new value to the end.

Perhaps something similar to:

const newValue = {field1: 2, field2: 6};

db.collection.update({match criteria},
    [{$set:{
         array:{
             $cond:{
               if: {$in: [newValue.field1, "$array.field1"]},
               then: "$array",
               else: {$concatArrays: ["$array", [newValue]]}]}
             }
         }
     }}]
)
Sign up to request clarification or add additional context in comments.

2 Comments

What if I need to update a value on the existing item in the array if the fild1 is indeed present ?
If the change is too complex to put on the then line, take a look at using $reduce

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.