Copy and Insert a document on Same collection

3,199 views
Skip to first unread message

Asoka Sampath Edussooriya

unread,
Nov 27, 2011, 1:17:54 AM11/27/11
to mongod...@googlegroups.com
Hi,

Can anyone help me to copy and insert a document in same collection. I tried following on mongo command shell. but it gives me an error. the reason is the same mongo _id. the whole document is going to copy including mongo _id. following is the way i have tried.

db.pages.find().limit(1).forEach(function(x){db.pages.insert(x)});

the error i got is -

E11000 duplicate key error index: XXXX.pages.$_id_  dup key: { : ObjId(4e98157f3b9f5f202e000000) }

Thanks!

Asoka


--
Asoka Sampath Edussooriya

Eliot Horowitz

unread,
Nov 27, 2011, 1:26:37 AM11/27/11
to mongod...@googlegroups.com
What are you trying to do exactly?

_id has to be unique.

You could do this:

> db.pages.find().limit(1).forEach(function(x){ delete x._id; db.pages.insert(x)});

> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.
>

Asoka Sampath Edussooriya

unread,
Nov 27, 2011, 1:30:18 AM11/27/11
to mongod...@googlegroups.com
Hi Eliot,

just a simple thing i want to do. duplicating a document with same fields with a new mongo _id.

Thanks!

Asoka
--
Asoka Sampath Edussooriya

Edi

unread,
Nov 27, 2011, 1:33:49 AM11/27/11
to mongodb-user
it works !. thanks !
Reply all
Reply to author
Forward
0 new messages