最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongodb delete subdocument - Stack Overflow

programmeradmin2浏览0评论

I'm trying to delete a subdocument in mongoDb but can't succeed in it. I've tried with $update,$push and $pull but I'm not successful.

I have the following document:

db.users.findOne({"_id": ObjectId("545677a9e4b0e0ef9379993c")})
{
    "_class" : ".xxx.xxx.server.da.User",
    "_id" : ObjectId("545677a9e4b0e0ef9379993c"),
    "bookSummaries" : [
        {
            "_id" : ObjectId("545677e7e4b0e0ef9379993d"),
            "isbn" : "2746969644"
            "title": "test title"
        },      
        {
            "_id" : ObjectId("546a522a44ae4f5e652fdca7"),           
            "loanSummaries" : [
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473992044aec466a619290c"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473997d44aec466a619290d"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "547605a744ae0f0d558ae757"
                }
            ],
            "testArray" : [
                {
                    "title" : "Back to the future",
                    "id" : "test"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test2"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test3"
                },
                "test ",
                "test ",
                "test 2",
                "test 2",
                {
                    "loanStatus" : "REQUESTED"
                }
            ],
            "title" : "Back to the future"
        }
    ]
}

and I'm trying to create the queries to:

  1. delete the whole "testArray" subdocument for only this specific subdocument
  2. delete a specific loanSummaries give its loanId for this specific subdocument

Can you help me creating those queries? I've seen several post like this one, but it is not the same problem.

Thanks a lot

I'm trying to delete a subdocument in mongoDb but can't succeed in it. I've tried with $update,$push and $pull but I'm not successful.

I have the following document:

db.users.findOne({"_id": ObjectId("545677a9e4b0e0ef9379993c")})
{
    "_class" : ".xxx.xxx.server.da.User",
    "_id" : ObjectId("545677a9e4b0e0ef9379993c"),
    "bookSummaries" : [
        {
            "_id" : ObjectId("545677e7e4b0e0ef9379993d"),
            "isbn" : "2746969644"
            "title": "test title"
        },      
        {
            "_id" : ObjectId("546a522a44ae4f5e652fdca7"),           
            "loanSummaries" : [
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473992044aec466a619290c"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473997d44aec466a619290d"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "547605a744ae0f0d558ae757"
                }
            ],
            "testArray" : [
                {
                    "title" : "Back to the future",
                    "id" : "test"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test2"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test3"
                },
                "test ",
                "test ",
                "test 2",
                "test 2",
                {
                    "loanStatus" : "REQUESTED"
                }
            ],
            "title" : "Back to the future"
        }
    ]
}

and I'm trying to create the queries to:

  1. delete the whole "testArray" subdocument for only this specific subdocument
  2. delete a specific loanSummaries give its loanId for this specific subdocument

Can you help me creating those queries? I've seen several post like this one, but it is not the same problem.

Thanks a lot

Share Improve this question edited Jan 17, 2016 at 17:40 cbass 2,5583 gold badges29 silver badges39 bronze badges asked Dec 20, 2014 at 10:50 choukchouk 2895 silver badges14 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 2

I recently had the same problem where I had to remove a nested subarray. In the query you need to identify the exact object that you want to remove, and then in your update query you can use the $ sign as index for the object in the array that you want to pull.

var query = {
       "_id" : ObjectId(someUserId),
       "bookSummaries._id" : ObjectId(bookId), //might also work with isbn as long as it is uniq
       "bookSummaries.loanSummaries.loanId" : loanId
 };

var updateQuery = {
      "$pull" : {
          "bookSummaries.$.loanSummaries" : {
                 "loanId": loadId
          }
      }
}

Update

I tried the following queries in my shell which worked fine. You will have to enter the appropirate ids.

var query = { "_id" : ObjectId("53b73b1108fe927c0e00007f"),  "bookSummaries._id" : ObjectId("53b73b1108fe927c0e00007f"), "bookSummaries.loanSummaries.loanId" : "53b73b1108fe927c0e00007f" }

var updateQuery = { "$pull" : { "bookSummaries.$.loanSummaries" : {  "loanId": "53b73b1108fe927c0e00007f"  } } }

Update 2

If you already know the index of item/object you want to remove you can use the queries below in order to achieve this.

Find the document you want to edit

var query = {
   "_id" : ObjectId(someUserId),
};

Unset the object you want to remove

var update1 = {
  "$unset" : {
      "bookSummaries.1.loanSummaries.2" : 1
  }
}

Pull the object which has the value null.

var update2 = {
  "$pull" : {
      "bookSummaries.1.loanSummaries" : null
  }
}

And to remove you can basically use the same queries.

Find the document you want to edit

var query = {
   "_id" : ObjectId(someUserId),
};

Unset the object you want to remove

var update1 = {
  "$unset" : {
      "bookSummaries.0.testArray" : 1
  }
} 

I had to do something similar but delete multiple subdocuments instead of just one. My query included an array of ids and this worked for me:

User.updateOne(
      { _id: userId },
      {
        $pull: { bookSummaries: { _id: { $in: ids } } },
      });

Because MongoDB provides a full JavaScript environment you can easily manipulate the document and save the data back to the db.

*Note: if you are using MongoDB with php or python etc. there are equivalent ways to do that.

1.to delete whole "testArray" subdocument for only this specific subdocument for example index(1) do

db.users.find({"_id": ObjectId("545677a9e4b0e0ef9379993c")}).forEach(function (user) {
    delete user.bookSummaries[1].testArray;
    //Saveing the changes 
    db.users.save(user);
 });
  1. to delete a specific loanSummaries give its loanId for this specific subdocument for example id 5473992044aec466a619290c do

    db.users.find({"_id": ObjectId("545677a9e4b0e0ef9379993c")}).forEach(function (user) {
        var loanToDelete = "5473992044aec466a619290c";
        var loanIndexToDelete = -1;
    
        var i;
        for(i in user.bookSummaries[1].loanSummaries) {
            if(user.bookSummaries[1].loanSummaries[i].loanId === loanToDelete) {
                loanIndexToDelete = i;
                break;
            }
        }
    
        if (loanIndexToDelete > -1) {
          delete user.bookSummaries[1].loanSummaries[loanIndexToDelete];
        }
    
        //Saving the changes
        db.users.save(users);
    });
    
发布评论

评论列表(0)

  1. 暂无评论