Ozzyii BuckBar
Ozzyii BuckBar

Reputation: 3

how can i update field in array?

I want to be able to change one value in one of the objects in the courseDetail array.

This is a sample document from my database for clarity

courseDetail" : [ 
    {
        "_id" : ObjectId("5d3b50413a24137c39090084"),
        "contentDetail" : [ 
            {
                "isDelete" : true,
                "_id" : ObjectId("5d3b50413a2413cffa090085"),
                "course_content" : "Robotics EV3 Mindstorms 1",
                "times_amount" : 23,
                "times" : 234,
                "unit_id" : ObjectId("5d19d2ce9e0df904f81aeefb"),
                "ex" : 30,
                "price_2" : 1000,
                "price_1" : 2000
            }, 
            {
                "isDelete" : true,
                "_id" : ObjectId("5d56c654f1d8a20e00d2f5ab"),
                "course_content" : "lever 2",
                "times_amount" : 20,
                "times" : 20,
                "unit_id" : ObjectId("5d19d2ce9e0df904f81aeefb"),
                "ex" : 20,
                "price_2" : 2000,
                "price_1" : 2000
            }
        ],
        "course_content" : "Basic"
    }
]

Here is the query I have attempted, however, it is not working as I would expect it to.

$set: {"courseDetail.contentDetail.isDelete": false }

Upvotes: 0

Views: 38

Answers (1)

Matthew E. Miller
Matthew E. Miller

Reputation: 567

Since the object you are attempting to change a value on is an array, you need to specify an index. In your sample document, there are 2 objects in the array, so your index is either 0 or 1.

If you wanted to update the first item in the array, your query would look like this: $set: { "courseDetail.contentDetail.0.isDelete" : false }

(notice specifying an index to select an item from the array)

Here is some supporting documentation for the array operator in mongodb.

Upvotes: 1

Related Questions