Search code examples
node.jsmongodbputsubdocument

How can I update a subdocument in MongoDB?


Code created in Mongoose to update a subdocument was not working. So I tried to update the subdocument within the Mongo Shell.
This is the document (location) and subdocument (review):

{
"_id" : ObjectId("56d8c73314fbc7e702cfb8c4"),
"name" : "Costly",
"address" : "150, Super Street",
"coords" : [
    -0.9630884,
    51.451041
],
"reviews" : [
    {
        "author" : "kyle riggen1",
        "_id" : ObjectId("56d8de74cc7f953efd8455d9"),
        "rating" : 4,
        "timestamp" : ISODate("2015-06-01T06:00:00Z"),
        "reviewText" : "will the ID work?"
    }
],
"rating" : 0,
"__v" : 2

}

Here are some of my attempts at updating the subdocument:
This question gave this format:

update({ 
       _id: "56d8c73314fbc7e702cfb8c4", 
       "reviews._id": ObjectId("56d8de74cc7f953efd8455d9")
   },{
       $set: {"reviews.$.rating": 1}
   }, false, true
);

This returned an error of "update is not defined" as shown:

2016-03-03T22:52:44.445-0700 E QUERY    [thread1] ReferenceError: update is not defined :
@(shell):1:1

Which I think is because the command did not start with db.locations.update()

MongoDB documentation used this format:

db.locations.update(
   {
     _id: "56d8c73314fbc7e702cfb8c4",
     review: { $elemMatch: { author: "kyle riggen1" } }
   },
   { $set: { "location.$.rating" : 1 } }
)

This returns a valid update but the update didn't actually happen as shown:

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

This question used this format:

db.locations.update({
    _id: "56d8c73314fbc7e702cfb8c4",
    'review.author': 'kyle riggen1'
  },
  { $set: { 'review.$.rating': 1 }}
)

This returns the same as the MongoDB documentation as shown here:

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

So these queries I guess are working but my data is not getting updated. Would my data be indexed wrong perhaps? The actual location is able to be updated even through a Mongoose API.


Solution

  • You can do it By $push Or $addToSet.

    db.col.update(
            { name: 'reviews', 'list.id': 2 }, 
            {$push: {'list.$.items': {id: 5, name: 'item5'}}}
        )
    

    See the reference from mongodb Manual

    https://docs.mongodb.org/manual/reference/operator/update/push/