How to delete specific id in a mongodb database?

mongodb remove document by _id
delete collection mongodb
mongodb delete by _id nodejs
mongoose delete by id
mongodb delete many by _id
collection remove
mongodb remove document by _id java
mongodb remove vs delete

I am using nodejs,express, mongodb and mongoose here! It happens that i am trying to delete some of the ID's that are inside the "followers" document...

This is the part of the model ( I am just copying this part because it is the one that interests me):

  var UserSchema = new mongoose.Schema({
     followers: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        }
})

I am trying to delete using this code:

try{
    let user = await User.findById(req.params.id);
    user.followers.remove({_id: ObjectId(req.user._id)});
    user.save();
  }
  catch(err) {
    res.redirect('back');
  }

The req.user._id is the ID of the user which I am trying to delete from the "followers", however, whenever I execute this, the page just keeps loading and nothing happens.=The follower that I want to delete is not being deleted. Can someone help me with it?

You can deletedocuments within an Array by using $pull In single Query

Query :

db.getCollection('users')
  .update({ "_id": ObjectId("5bb4747f316fcf310f3ef0a4") },
    { $pull: { followers: { _id: ObjectId('5bb4747f316fcf310f3ef0a5') } } },
    { multi: true })

Tested on Mongo GUI.

Test on below doc

{
    "_id" : ObjectId("5bb4747f316fcf310f3ef0a4"),
    "index" : "123456",
    "followers" : [ 
        {
            "_id" : ObjectId("5bb4747f316fcf310f3ef0a6"),
            "name" : "green"
        },
       {
            "_id" : ObjectId("5bb4747f316fcf310f3ef0a5"),
            "name" : "green"
        }
    ]
  }

Remove, MongoDB Delete Document: In this tutorial we will learn how to delete Now I want to remove the student from this collection who has a student id equal to  To delete or drop a database from MongoDB, follow the below steps : Select the database you want to delete with the help of USE <database> command. Following is the syntax of USE command : use <database_name>. Drop the database with the help of db.dropDatabase () command.

Ok guys, so I found the problem: It looks like after adding this "{_id: ObjectId(req.user._id)}" the followers were actually being deleted... The page did not stop loading because i forgot to put a res.redirect after the user.save()! =D This is the code after I fixed it:

try{
    let user = await User.findById(req.params.id);
    user.followers.remove({_id: ObjectId(req.user._id)});
    user.save();
    req.flash('success','Successfully unfollowed '+user.username +"!");
    res.redirect('/users/'+ req.params.id);
  }
  catch(err) {
    req.flash('error', err.message);
    res.redirect('back');

  }

MongoDB Delete Document from a Collection, To delete multiple ids in MongoDB, you can use $in operator. Following is the syntax db.yourCollectionName.remove( { _id : { $in:  In MongoDB 4.0 and earlier: If you drop a database and create a new database with the same name, you must either restart all mongos instances, or use the flushRouterConfig command on all mongos instances before reading or writing to that database.

You can use:

A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options)  // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove()

for example 01:

Example.findByIdAndRemove(example._id, function(err, foundExample) {
    console.log("you removed" + foundExample);
})

for example 02:

Example.findByIdAndRemove({_id: numberOfId}, function(err) {
    if(!err){
       console.log("successfully removed")
    })
  })

for example 03:

Example.findByIdAndRemove({_id: numberOfId}, async function(err) {
    if(!err){
       await console.log("successfully removed");
    })
  })

How to delete multiple ids in MongoDB?, MongoDB - Delete Document - In this chapter, we will learn how to delete a remove() method is used to remove a document from the collection. remove() method title: "NoSQL Overview"}, {_id : ObjectId("507f191e810c19729de860e3​"), title: If there are multiple records and you want to delete only the first record, then  This C# Quick Start series has covered the various CRUD Operations (Create, Read, Update, and Delete) operations in MongoDB using basic BSON Documents. We've seen how to use filters to match specific documents that we want to read, update, or delete. This series has, thus far, been a gentle introduction to C Sharp and MongoDB.

MongoDB - Delete Document, I would like to delete specific data from MongoDB collection, for an example i have collection { "_id" : ObjectId("51628065bc6dba386dc6834e"),  Iterate a Cursor in the mongo Shell. Update Documents. Updates with Aggregation Pipeline. Delete Documents. Bulk Write Operations. Retryable Writes. SQL to MongoDB Mapping Chart. Text Search Operators. Text Search in the Aggregation Pipeline. Text Search Languages. Geospatial Queries. Find Restaurants with Geospatial Queries. GeoJSON Objects.

How to delete document by id from MongoDB?, Returns: A WriteResult object that contains the status of the operation. Sample document in the invoice collection: { "_id" : ObjectId  Delete Document. To delete a record, or document as it is called in MongoDB, we use the deleteOne () method. The first parameter of the deleteOne () method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.

db.collection.remove() - MongoDB shell method, The id field is unique for each document in a collection. Then how can the deleteMany() method delete multiple documents? There is a way to do  If you have not selected any database, then it will delete default 'test' database. Example. First, check the list of available databases by using the command, show dbs. >show dbs local 0.78125GB mydb 0.23012GB test 0.23012GB > If you want to delete new database <mydb>, then dropDatabase() command would be as follows −

Comments
  • could you put console.log(user) after await. I dont think the await is finish executing. somehow your program stuck there
  • Sagar, thank you, I found the problem using the console.log!
  • Thank you for it! I tried this just now and it also worked! What is the point of that "multi:true"?
  • Also its delete multiple if match
  • You can remove if you required to delete only one value