3

In mongo I have a collections with records. These record are very complex. Now I would like to duplicate one of them.

I can easily select the one

mongo> var row = db.barfoo.find({"name":"bar"});

Now I actually don't know what to do. I don't know what is in row because I cannot find a way to print its content. How can I change specific properties and finally insert this modified row again

mongo> db.barfoo.insert(row);

thnx

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

2 Answers2

7

You must change value _id - generate new:

var row = db.barfoo.findOne({"name":"bar"});
row._id = ObjectId();
db.barfoo.insert(row);

Good Luck!

Gh0stik
  • 145
  • 6
  • 2
    Mongo will create an `_id` attribute if one is missing. I don't think that you have to manually create it like this - [see here](http://docs.mongodb.org/manual/reference/object-id/) – Lix Mar 11 '14 at 12:18
  • @Lix I'm using mongo 3.2.8 and I needed the `_id` creation to get this to work. – chakeda Nov 17 '16 at 18:14
1

I am going to assume that you're working directly inside the mongo shell.

Once you have your document (not a row :P ), you'd modify the properties in the same way you would a normal JavaScript object:

var doc = db.barfoo.findOne( { "name": "bar" } );
doc.name = "Mr Bar";

Note that the find() command returns a cursor, so if you're looking to extract a single document, you should use the findOne() function. This function returns a single document.

If you are interested in duplicating numerous documents, you can use the find() function and iterate over the cursor to retrieve each document:

db.barfoo.find( { "name": "bar" } ).forEach( function( doc ){
  doc.name = "Mr Bar";
}

After you change the relevant properties, you can use the insert/save methods to persist the data back to mongo. Don't forget to change/delete the _id attribute so that you'll actually create a new document.


As a side note, in order to view the contents of an object in the mongo shell, you can use the print() function. If you want a more visually appealing output, you could use printjson().

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    Doesn't `find` return a cursor? He should iterate through it to actually get the name (or record), shouldn't he? – martskins Mar 11 '14 at 12:13
  • 1
    I'm sure you mean `findOne` not `find_one` :P – martskins Mar 11 '14 at 12:16
  • @lascort ARRGGHH!!!! Jumping from language to language always trips me up! You're very patient with your downvotes ;) – Lix Mar 11 '14 at 12:17
  • So I have a variable that contains a large amount of documents. When I execute the forEach on it, it completely breaks and returns nothing without any error messages, and erases the contents of the var previously containing an array of documents – Aymon Fournier Aug 11 '16 at 00:11
  • Hi @AymonFournier - please create a new post if you have a different question from this one. – Lix Aug 11 '16 at 07:14