0

I'm trying to remove a lesson based on lesson_id from the following.

{
    "_id" : ObjectId("5807f3f"),
    "title" : "Title",
    "lessons" : [
        {
            "lesson_id" : ObjectId("58073"),
            "_id" : ObjectId("58074")
        },
        {
            "lesson_id" : ObjectId("5807f5"),
            "_id" : ObjectId("5807f6")
        },
        {
            "lesson_id" : ObjectId("58077"),
            "_id" : ObjectId("5807f4")
        }
    ],
    "__v" : 0
}

I've tried $pull and $unset, but with both my code seems to just set lessons.lesson_id to null and keep the lessons._id

Is there anyway to remove both from the object?

module.exports.deleteLessonFromClass = function(id, lesson_id, callback){   Class.update(
        {'_id': id}, 
        { $unset: {lessons: {lesson_id: lesson_id}}},
        callback
    ) }
John Doe
  • 1
  • 1
  • Possible duplicate of [MongoDB, remove object from array](http://stackoverflow.com/questions/15641492/mongodb-remove-object-from-array) – TomG Oct 20 '16 at 07:59

1 Answers1

1

Try the following query:

db.collection.update(
    { "_id" : <id> },
    { $pull : { "lessons" : { "lesson_id" : <lesson_id> } } }
);

This will find a document by <id> and remove its <lesson_id> from its lessons array.

Hope this helps.

  • 1
    Your `lesson_id` is an `ObjectId`, So you have to have it like the following: `"lesson_id" : ObjectId("yourObjectId")` –  Oct 20 '16 at 00:09