How do I manually add a reference in MongoDB? How do I manually add a reference in MongoDB? mongodb mongodb

How do I manually add a reference in MongoDB?


This worked for me from the MongoDB shell, I'm using $addToSet instead of $push because I assume you want to avoid dupes:

var o = new ObjectId();db.foo.update({}, {$addToSet : {"contacts" : o}});var o = new ObjectId();db.foo.update({}, {$addToSet : {"contacts" : o}});

That gave me a document that looks like this (my foo collection only contained your sample, so I didn't have to have a specific matching criteria):

{    "_id" : ObjectId("500c2118c78bb07bfbb69eb3"),    "contacts" : [        ObjectId("500c20efc78bb07bfbb69eb2"),        ObjectId("500c227ac78bb07bfbb69eb6")    ],    "email" : "kyogron@example.de",    "username" : "kyogron"}


In mongo shell run the following update:

db.collection.update({"_id" : ObjectId("500abe6a25dff13c7c000001")},                     {$push:{"contacts": ObjectId("500abe6a2543213c7c000002")}})

Use appropriate ObjectId values for your specific case.