1

In my collection I have few docs with some having _id field as string and some others as type ObjectId

{_id:"xxxx"}
{_id:"yyyy"}
{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}

I want to delete _id field type ObjectId(here last docs)

Is there any solution for this?

Sasikanth
  • 3,045
  • 1
  • 22
  • 45

4 Answers4

2

If your document has ObjectId you can use $type

For Example if your collection is like

{
    "_id" : "foo"
}


{
    "_id" : "bar"
}


{
    "_id" : ObjectId("546c52074e418d78ff419897")
}


{
    "_id" : ObjectId("546c52074e418d78ff419898")
}

Remove Only ObjectId

db.coll.remove({_id:{$type:7}})

if your ObjectId is like

{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}

you can do it

db.coll.remove({"_id": {$regex:"^ObjectId"}})

if you want delete only one Document

db.coll.remove({"_id": {$regex:"^ObjectId"}},{justOne:true})

obviously, a specific _id

db.coll.remove({"_id" : "ObjectId(xxxssssx)"})
Barno
  • 3,271
  • 5
  • 28
  • 58
  • When I run `db.coll.remove({_id:{$type:7}})` all the docs in the collection are deleted, I have backup though :) – Sasikanth Nov 19 '14 at 10:11
  • @iAmME with `db.coll.remove({_id:{$type:7}})` remove Only ObjectId http://docs.mongodb.org/manual/reference/operator/query/type/.Maybe you have write wrong. With your documents, nothing is deleted, because they aren't "real" `ObjectId` but they are `string` – Barno Nov 19 '14 at 12:15
  • With your documents `{_id:"xxxx"} {_id:"yyyy"} {_id:"ObjectId(zzz)"} {_id:"ObjectId(xxxssssx)"}`, nothing is deleted. Then you have to use `$regex` – Barno Nov 19 '14 at 12:23
0

For deleting object you should write in new ObjectId so below query deleted only given object Id

db.collectioName.remove({"_id":new ObjectId("xxxssssx")})

or simply try this

db.collectioName.remove({"_id": ObjectId("xxxssssx")})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
0

As you cannot update an id How update the _id of one MongoDB Document? You should delete your documents and insert them again as code below do this.

db.test.find().forEach(function(item)
{
    if(typeof item._id == 'object')
    {                  
        var id = item._id.toString().replace('ObjectId(', '').replace(')', '');               
        db.test.remove({'_id': item._id});

        item._id = id;
        db.test.insert(item);
    }
});
Community
  • 1
  • 1
Disposer
  • 6,201
  • 4
  • 31
  • 38
0

You could make use of the $type operator. The type of Object Id is 7.

 db.collection.remove({"_id":{$type:7}})

This removes all the documents having the _id fields represented as Object Ids.

BatScream
  • 19,260
  • 4
  • 52
  • 68