I have a mongo document like this.
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "b"
}
],
"tester" : "tom"
}
I want to be able to insert and update the array
with a single mongo command and not use a conditional within a find()
then run insert()
and update()
depending on the presence of the object.
The id
is the item I want to be the selector. So if I update the array with this:
{
"id" : "2",
"letter" : "c"
}
I have to use a $set
statement
db.soup.update({
"tester":"tom",
'array.id': '2'
}, {
$set: {
'array.$.letter': 'c'
}
})
And if I want to insert a new object into the array
{
"id" : "3",
"letter" : "d"
}
I have to use a $push
statement
db.soup.update({
"tester":"tom"
}, {
$push: {
'array': {
"id": "3",
"letter": "d"
}
}
})
I need a sort of upsert for an array item.
Do I have to do this programmatically or can I do this with a single mongo call?