Java Programming Tutorials

Java programming tutorials with many code examples!

MongoDB update document in array

MongoDB has plenty of cool features to work with documents, but I found it less than obvious how to update document in array. So here it is…

Collection with array of documents

Test collection has documents with simple structure, where we keep authors as documents in an array:

{
  "_id" : ObjectId("58d7fcdf2ef1a79af37f59b0"),
  "title" : "Clean code",
  "authors" : [
     { "name" : "Robert C. Martin" }
  ]
}

Update document in array

Now, we want to patch document in array of authors. To do that we have to specify which document we want to update and which document in the array. If you don’t specify nested document, then you’ll see error 16837:

The positional operator did not find the match needed from the query. Unexpanded update: authors.$.name

Therefore the full update command looks like this:

db.books.update(
  {
    "_id" : ObjectId("58d7fcdf2ef1a79af37f59b0"),
    "authors.name": "Robert C. Martin"
  },
  {
    $set: {"authors.$.name": "Uncle Bob"}
  }
)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

In the $set part of the update we refer to matching document in the array using $ (dollar sign). It is the position of the first array document that matches.

Now the document in the array has updated content:

db.books.find()
{
  "_id" : ObjectId("58d7fcdf2ef1a79af37f59b0"),
  "title" : "Clean code",
  "authors" : [
    { "name" : "Uncle Bob" }
  ]
}

References:

Share with the World!