mongodbfindandmodify

MongoDB: Update an array using FindAndUpdate()


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

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?


Solution

  • 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}
    })