3

I want to add an element to the array and add new field to the database if result of the query is an insert. If it is not an insert(if it is a update) I don't want to update the array and add new field.

To add new field on insert; I use $setOnInsert.

To add element to the array I use, $addToSet: { "children": {"age": 12}},

I tried but it seems that it is not possible to use $addToSet inside $setOnInsert. So how can add an array element if it is an insert?

1 Answer 1

3

Because the doc is being created in the insert case, you would just create the initial children array with that element:

{$setOnInsert: {children: [{age: 12}]}}
Sign up to request clarification or add additional context in comments.

4 Comments

But, array of children already has some elements? Actually, that was why I use $addToSet or $push. This way, children array will be erased, am I wrong?
$setOnInsert is only used in the insert case where the document doesn't exist, so there can't already be children array elements.
@YigitCan If I'm misunderstanding your question, can you add details to your post about the specific case this won't work for?
You're right about children elements, the answer works, thank you so much.

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.