Home > Blockchain >  How I can remove only one object in mongodb, not all objects matching the filter query?
How I can remove only one object in mongodb, not all objects matching the filter query?

Time:05-09

This is my code for deleting object containg name as 'bob':

app.delete('/user/:id', async (req, res) => {
            const id = req.params.id;
            const query = { name: "bob" }
            const result = await userCollection.deleteOne(query);
            res.send(result);
 });

This code delete all objects that have name as 'bob', but I want to delete any one instance only from db matching this query, not all objects. And is there any way to set count that how many instance I want to delete matching this query?

CodePudding user response:

You can use this code

const ObjectId = require("mongodb").ObjectId;
app.delete('/user/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const result = await userCollection.deleteOne(query);
            res.send(result);
 });
  • Related