I would like to add a document if it does not exist and else add an element to one of it's sub-documents.
db.test.update(
{
name : 'Peter'
},
$setOnInsert : {
name : 'Peter',
visits: { 'en' : ['today'], 'us' : [] }
},
$push : {
visits.en : 'today'
},
{ upsert : true }
)
If Peter
exists, add an element to its visists.en
or visists.us
arrays. Else, create a document for Peter
. This document should have the format for visits
which should contain the current element ('today'
).
My issue is that I have "have conflicting mods in update"
.
I.e. (afaik), I cannot write to two things in one query. Yet how can I solve this dilemma?
You could implement it without $setOnInsert
operator.
db.test.update(
{
name : 'Peter'
},
{
$push : {
"visits.en" : 'today'
}
},
{ upsert : true }
)
If Peter exists, element 'today'
will be added to its visits.en
array. Else, will be created a document for Peter, with visits
object, that will be contain array en
with 'today'
element.
And I think, that error occured because of you using same property (visits
) in two operations ($setOnInsert
and $push
).
You can still use $setOnInsert
but when $setOnInsert
and $push
doesn't updates in the same fields as mentioned before.
N.b: We use $addToSet
if you don't want a duplicated values in your Array
db.test.update(
{
name : 'Peter'
},
{
$setOnInsert: {name : 'Peter'},
$addToSet: {"visits.en": 'today'} // or $push
},
{upsert: true})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With