Solomon david
Solomon david

Reputation: 92

Insert Documents to specific ID in MongoDB

i am trying to insert a document into a specific ID (ID generated Default by mongoDB) like we do in mysql (INSERT WHERE id="985264").

app.get('/', function(req , res){
db.facebook.insert({
_id:985264,
 username: "Solomon.david",
 status : "i love to code and eat",
 comments: [
{
  user : "jackson",
  comment: "even me "
}
]
  }, function(err,docs){
 res.render('won.html');     
  });
}); 

Upvotes: 6

Views: 31928

Answers (2)

mohamedrias
mohamedrias

Reputation: 18576

As per your comment:

i am trying to create a comment system when a user submits his/her comment to a specific photo with a unique ID (which the mongoDB creates by default ) it should inserted in to that particular photo –

  1. I understand that you have a photos collection where each photo as a unique ID.

  2. When the user submits a comment to a specific photo that comment must be inserted in that photo

It's a typical update operation, as you will be updating the photo document with the comment being inserted in the array.

{
   _id :  ObjectId("536f710fc55b2acc61000bc9"),
   foo: "foo",
   bar : "bar",
   comments: [
   {
      user : "userId",
      comment: "The photo is nice"
   }
   ]
}

So your query will be:

db.photocollection.update(
   {_id: ObjectId("536f710fc55b2acc61000bc9")},
   {$push : {
             comments : {
               user: "userid",
               comment: "photo is awesome"
               }
          }
    }
)

All the comments are inserted in the same photo document.

Note: If you feel that the number comments will grow a lot over time, then its better to reference the comments instead of embedding.

Hope its useful to you!

Upvotes: 9

Lix
Lix

Reputation: 48006

All you have to do is specify the _id attribute within the document you are trying to insert:

db.collection.insert( { "_id": "unique_id", "foo": "bar", ... } )

As mentioned in the documentation, there are a few considerations that you should take care to enforce - namely, you need to ensure that the _id you have specified is unique.


Taken from the linked documentation page:

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.

Upvotes: 11

Related Questions