Reputation: 99
I am using mongoose v5.13 on NodeJS
For a document whose id I know
{
_id: ...,
edible: 'fruit'
}
I want to update
this document and do this
if (obj.edible == 'fruit') {
obj.edible = 'apple';
} else if(obj.edible == 'vegetable') {
obj.edible = 'carrot';
}
But this requires me to find first and then update, hence, two queries, my question is can I do it in one operation
Upvotes: 0
Views: 77
Reputation: 8695
Query
$cond
also, but i used $switch
so you can add more if neededupdate(
{"_id": {"$eq": 1}},
[{"$set":
{"edible":
{"$switch":
{"branches":
[{"case": {"$eq": ["$edible", "fruit"]}, "then": "apple"},
{"case": {"$eq": ["$edible", "vegetable"]}, "then": "carrot"}],
"default": "unknown"}}}}])
Upvotes: 1
Reputation: 327
db.collection.update(
{
_id: ObjectId("61723c7378b6d3a5a02d908e")
},
[
{
$set: {
edible: {
$switch: {
branches: [
{ case: { $eq: [ "$edible", 'fruit' ] }, then: "apple" },
{ case: { $eq: [ "$edible", 'vegetable' ] }, then: "carrot" }
],
default: "$edible"
}
}
}
}
])
Upvotes: 2