Despicable
Despicable

Reputation: 3957

Document inside document in MongoDB

I am trying to insert multiple objects in one field. Here is the example.

I have a collection of Questions whose fields are Q_ID, Q_Question and Q_ANS.

Now, the user posts a question and it goes into:

Now, the other users will post answers.

How can I insert multiple answers, one by one, in Q_ANS? I tried

db.Questions.update({ans:'this is ans'},{$set:{Q_ID:1}})

but it just replaced the previous answer. I want to insert all answers in Q_ANS one by one as they were posted.

Upvotes: 0

Views: 1062

Answers (1)

leojg
leojg

Reputation: 1186

You should use $addToSet

db.Questions.update({ans:'this is ans'},{$addToSet:{Q_ID:1}})

If the documents are identicall this will update it.

If you want to add and do not care about duplicates, yu can use $push

db.Questions.update({ans:'this is ans'},{$push:{Q_ID:1}})

Edit:

This links can help you a bit

http://docs.mongodb.org/manual/reference/operator/update/push/ http://docs.mongodb.org/manual/reference/operator/update/addToSet/

Upvotes: 2

Related Questions