Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-6566

Support conditional updates: $updates

    XMLWordPrintable

    Details

      Description

      Add support for multiple conditional updates in a single update operation. An array of match + update will be executed against each found document. All positional matching is done on the update match, not the query. See below for examples.

      db.coll.update( query, {$updates: [
      	{when:{a:null}, do:{$set:{a:3}}}, // if missing or null set it
      	{when:{_id:null}, do:{ $set:/* initial values */}}, // same as $setOnInsert since _id will be null/missing
      	
      	{when:{votes:{$lt:19}}, do:{$inc:{votes:1}}},// max for field of 20
      	{when:{votes:{$gt:20}}, do:{$set:{votes:20}}},// max for field of 20, cleanup bad values
      	
      	{when:{tags:{$ne:null}}}, do:{$push:{tags:"a"}}},// $push if tags array exists
      	{when:{tags:null}, do:{$set:{tags:["a"]}}},// replace null with tags array if incorrectly set to null
      	
      	{when:{$not: {"users.id":"scott"}}, do:{$push:{users:{id:"scott", views:0 }}}},// Support for "push if missing" (kinda like upsert for arrays)
      	{when:{"users.id":"scott"}, do:{$inc:{"users.$.views:1 }}},
       
      	//SERVER-1014 example $pull first match of 2 in array
      	{when:{vals:2}, do:{$unset:{"vals.$":true}}},// unset array element (sets to null)
      	{when:{vals:null}, do:{$pull:{vals:null}},// remove nulls from array
       
      	//SERVER-1050 example (no match/do needed -- unconditional)
      	{$push:{vals:-200}},
      	{$pop:{vals:-1}}},
       
      	//SERVER-1947 $set w/positional and $push to same array
      	{$set: { "version" : 2, "name" : "NEWNAME"}, $inc: {"versionsCount" : 1 }, $push: {"versions" : { "z" : "anewone" }}}
      	{when:{ "versions.version" : 1}, do:{$inc:{"versions.$.versionToInstant" : 1000}}}
      ]})

      The server would execute the query, run through each conditional update element in the array (in order) and apply the update only if the match succeeds for the document.

        Attachments

          Issue Links

            Activity

              People

              • Votes:
                36 Vote for this issue
                Watchers:
                42 Start watching this issue

                Dates

                • Created:
                  Updated: