Reputation: 23
I have this code
{
"_id" : ObjectId("573308a2519d9ff8820e7be8"),
"id" : "Example",
"Test" : [
"InsertB1",
"InsertB2"
],
"num" : 2
}
I would like to use the function findAndUpdate
because I would like to
"InsertB1"
to "UpdateB1"
"num"
from 2 to 3.I've written this one, but does not work...
db.Collection.findAndModify({
query: {
id:"Example",
num:{ $lt: 3 }
},
update: {
id:"Example",
Test: "InsertB1",
$set: { "Test.$": "Update1" },
$inc: { num: 1 }
},
upsert:true,
new:true
})
How can I modify my code?
Upvotes: 2
Views: 803
Reputation: 11132
You forgot to include the array-element you'd like to update in the query.
The $
refers to the first matching array element addressed in the query, if want to update "InsertB1", you have to add that.
Try use this
var oldDoc = db.Collection.findAndModify({
query: {
id:"Example",
num: {$lt:3},
Test: "InsertB1"
},
update: {
$set : {"Test.$": "Update1"},
$inc: {num : 1 }}
},
upsert: true)
If returning the old (or new) document is not required, you may stick to the update command
db.Collection.update({
id:"Example",
Test: "InsertB1",
num: {$lt:3}
},{
$set : { "Test.$": "Update1"},
$inc: {num : 1}
})
Upvotes: 2