173

In the MongoDB console how can I remove a record by id? Here's my collection :

[ 
  {
     "_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
     "name" : "Gazza"
  },
  {
     "_id" : { "$oid" : "4d513345cc9374271b02ec6c" },
     "name" : "Dave",
     "adminOf" : { },
     "email" : "email@email.com"
  }
]

And here are the commands I've tried that don't work :

db.test_users.remove( {"_id":{"$oid":new ObjectId("4d512b45cc9374271b02ec4f")}});
db.test_users.remove( {"_id":{"$oid":"4d513345cc9374271b02ec6c"}});
db.test_users.remove( {"_id":"4d512b45cc9374271b02ec4f"});
db.test_users.remove( {"_id":new ObjectId("4d512b45cc9374271b02ec4f")});

Removing by name works :

db.test_users.remove( {"name":"Gazza"});

This is in the browser shell on at mongodb.org if that makes any difference.

starball
  • 20,030
  • 7
  • 43
  • 238
Typo Johnson
  • 5,974
  • 6
  • 29
  • 40
  • None of the solutions worked for me until I added a callback: db.test_users.remove( {"_id": '4d512b45cc9374271b02ec4f'}, function(err, data){}); – rttmax Jun 13 '16 at 14:45
  • I am courious how you succeded to write those documents in your collection , my attempt ended with "writeError" : { "code" : 52, "errmsg" : "$oid is not valid for storage." } – R2D2 Jan 20 '21 at 20:53
  • we need to write it in this way to make it work db.student.remove({ "_id" : ObjectId("627f593641bcd9e215bc949d")}) OUTPUT: WriteResult({ "nRemoved" : 1 }) – Priyesh Ranjan May 14 '22 at 07:34

15 Answers15

328

Very close. This will work:

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});

i.e. you don't need a new for the ObjectId.

Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
  • 4
    it will work also without quotes around _id db.test_users.remove( {_id: ObjectId("4d512b45cc9374271b02ec4f")}); – alfonsodev Jan 04 '14 at 19:06
  • I tried this: TimeAndSpace.remove( {"_id": ObjectId("8Bd2dZ778LXejYNrL")}); ...and I got, "Uncaught ReferenceError: ObjectId is not defined at :2:13" – B. Clay Shannon-B. Crow Raven Aug 11 '15 at 02:57
  • @BClay The object ID expects hexadecimal input (maybe also lowercase) so it's failing on the X, Z characters amongst others. – Nic Cottrell Aug 11 '15 at 08:19
  • If the `_id` field is not automatically generated (i.e. it is not an ObjectId, but a String), You can just write the value of the `_id` under quotation marks: `db.your.database.remove({"_id": "your value"})`. – Aleksandar Jun 04 '18 at 16:39
  • 1
    DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead – Ramesh Vishnoi Mar 08 '20 at 09:44
23

If you would like to remove by a list of IDs this works great.

db.CollectionName.remove({
    "_id": {
        $in: [
            ObjectId("0930292929292929292929"),
            ObjectId("0920292929292929292929")
        ]
     }
}) 
fullerja
  • 143
  • 1
  • 11
mjwrazor
  • 1,866
  • 2
  • 26
  • 42
19

Well, the _id is an object in your example, so you just need to pass an object

'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'
starball
  • 20,030
  • 7
  • 43
  • 238
Dmitri
  • 34,780
  • 9
  • 39
  • 55
17

The answer is that the web console/shell at mongodb.org behaves differently and not as I expected it to. An installed version at home worked perfectly without problem ie; the auto generated _id on the web shell was saved like this :

"_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },

The same document setup at home and the auto generated _id was saved like this :

"_id" : ObjectId("4d5192665777000000005490")

Queries worked against the latter without problem.

Typo Johnson
  • 5,974
  • 6
  • 29
  • 40
  • 1
    Are you sure that they're saved differently in the document BSON? Those differences look like it's the client just formatting the output differently. – Nic Cottrell Aug 11 '15 at 14:50
8

first get the ObjectID function from the mongodb ObjectId = require(mongodb).ObjectID;

then you can call the _id with the delete function

"_id" : ObjectId("4d5192665777000000005490")

SA Khan
  • 89
  • 1
  • 3
8

Do you have multiple mongodb nodes in a replica set?

I found (I am using via Robomongo gui mongo shell, I guess same applies in other cases) that the correct remove syntax, i.e.

db.test_users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")})

...does not work unless you are connected to the primary node of the replica set.

Anentropic
  • 32,188
  • 12
  • 99
  • 147
7

I've just bumped into this myself and this variation worked for me:

db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})
Shoe
  • 74,840
  • 36
  • 166
  • 272
Karoy
  • 193
  • 3
  • 9
5
db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})
Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
kamula
  • 197
  • 2
  • 5
  • 1
    Please explain why/how this solves the problem. See [How To Answer](https://stackoverflow.com/help/how-to-answer) – jasie Sep 17 '20 at 07:55
4

Suppose we have this dummy collection:

{ "_id" : ObjectId("5ea53fedaa79db20d4e14284"), "item" : "planner", "qty" : 75 }

simply use:

db.inventory.deleteOne({ _id: ObjectId("5ea53fedaa79db20d4e14284") })

it will be deleted with this as a response:

{ "acknowledged" : true, "deletedCount" : 1 }
starball
  • 20,030
  • 7
  • 43
  • 238
Asad S
  • 2,096
  • 2
  • 11
  • 9
  • I have a document _id: ObjectId("6388df8324ce3a0e5c22b102") and other elements/fields. In my code I have projects.deleteOne_id({_id: ObjectId(id)} , where id = '6388df8324ce3a0e5c22b102'. When I run this I get an error data : {msg: 'ObjectId is not defined'}, If I try without "ObjectId" I get acknowledged: true, deletedCount: 0. Not deleting. – Pick Avana Dec 01 '22 at 17:27
3

Even though this post is outdated, collection.remove is deprecated! collection.delete_one should be used instead!

More information can be found here under #remove

Yuval Meshorer
  • 156
  • 2
  • 8
2
db.getCollection("test_users").deleteOne({_id: new ObjectId("4d512b45cc9374271b02ec4f")})

Attribution : To be fair this was the syntax used by a GUI client, the "Russian" one. Mine was a lurking duplicate cause by a bad "upsert" w/o the _id. It only showed up when adding a unique index.

mckenzm
  • 1,545
  • 1
  • 12
  • 19
1

1- C:\MongoDB\Server\3.2\bin>mongo (do not issue command yet because you are not connected to any database yet, you are only connected to database server mongodb).

2-

> show dbs
analytics_database  0.000GB
local               0.000GB
test_database       0.000GB

3-

> use test_database
switched to db test_database

4-

> db.Collection.remove({"_id": ObjectId("5694a3590f6d451c1500002e")}, 1);
WriteResult({ "nRemoved" : 1 })
>

now you see WriteResult({ "nRemoved" : 1 }) is 1 not 0.

starball
  • 20,030
  • 7
  • 43
  • 238
Dung
  • 19,199
  • 9
  • 59
  • 54
1

Execute the remove() method in this way

db.student.remove({ "_id" : ObjectId("627f593641bcd9e215bc949d")})
OUTPUT : WriteResult({ "nRemoved" : 1 })

enter image description here

Priyesh Ranjan
  • 111
  • 1
  • 3
0

There is new syntax. No need to pass keyword object Id. Just pass like this:

db.orders.remove({"_id":"62514d42f5aec503b2e0f2a9"})
starball
  • 20,030
  • 7
  • 43
  • 238
Aakash Handa
  • 1,215
  • 11
  • 18
0

There is a new way to delete the object key(ObjectId) i.e. store in _id column

  • const ObjectId = require("mongodb").ObjectId
  • db.collection.deleteOne({_id:**new ObjectId(id)**}) // without double quotes
starball
  • 20,030
  • 7
  • 43
  • 238