2

I have to insert an object {"category" : "Vehicle"} in the rated array below using Mongo shell commands. How can I do that?

 {
     "rating": {
         "userid": 1234,
         "bookingid": 4567,
         "rated": [
             {
                 "_id": "5aaa356f6b992b2068a1b691",
                 "category": "Driver",
                 "comment": "Good",
                 "rating": 5
             },
             {
                 "_id": "5aaa356f6b992b2068a1b690",
                 "category": "Overall",
                 "rating": 7
             }
         ]
     },
     "_id": "5aaa356f6b992b2068a1b68f",
     "__v": 0 }

2 Answers 2

4

It's quite simple. Use $push method to push an object into an array.

db.ratings.update(
   { _id: ObjectId('5aaa356f6b992b2068a1b68f') },
   { $push: { rated: {"category" : "Vehicle"} } }
)

Here, ratings is the collection name.

This will insert an object into the rated array.

Sign up to request clarification or add additional context in comments.

1 Comment

Please mark it right and do up if it is helpful. :)
0
db.collection.update({
        "_id": ObjectId("5aaa356f6b992b2068a1b68f")
    }, {
        $addToSet: {
            'rating.rated': {
                "category": "Vehicle"
            }
        }
    }

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.