Document inside document in MongoDB - 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:
Q_ID:1
Q_Question:'this is question'
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.

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/

Related

MongoDB Compass display fields in doc by order

Looking for a way to view the results of a query where the displayed fields in the doc are ordered (lexicographically in my case).
Example:
I'm getting back from a query one document, which is what I need. This document has 30 fields and I'm looking to see the value in one of them. My issue is that the order of the fields is, well, kinda random. Not sorted in any way I'm aware of.

Basic MongoDb Retrieval

I have two "documents" that I inserted into my MongoDB database.
questionsList.insert({question: "When was the War of 1812", answer: "1812", answers: ["1811", "1812", "1813", "1814"]})
questionsList.insert({question: "What year did the US land on the moon?", answer: "1969", answers: ["1969", "1970", "1971", "1972"]})
I simply want to access the answer value from the second document. I have been reading the documentation and it doesn't seem to work. I can retrieve the answer value from the first document without issue: var str = questionsList.findOne({}, {question: 1}).answer; I presume that since I am using findOne I can't find any other matches. The problem is that I can't seem to pull up the second document and its corresponding answer. I have tried many different ways:
questionList.find({}, {answer: 1})
questionList.find({answer: 1})
questionList.find({}).answer
My ultimate goal is to compare this answer with one of the click one answers from choices What am I missing?
If I understood your scenario correctly, you are trying to retrieve a document based on the document index (Which is not the right thing to do, since MongoDB does not store documents in specific order).
The reason why findOne works is, because it just returns the first document in your collection.
What I believe you should do instead is retrieve the answer based on the question. Something like:
db.questionsList.find({question:"What year did the US land on the moon?"},{answer:1})
Update:
In the case of meteor.js
questionsList.find({question:"What year did the US land on the moon?"}).fetch()[0].answer
The reason whey we need to give [0] is fetch() returns an array of objects. (Since there can be multiple documents with same key)
The final step is:
questionsList.find({"question": "You are human"}, {"answer": 1}).fetch()[0].answer
We are treating it as any other object (i.e. the first within a list of objects and using dot-notation)

how to join a collection and sort it, while limiting results in MongoDB

lets say I have 2 collections wherein each document may look like this:
Collection 1:
target:
_id,
comments:
[
{ _id,
message,
full_name
},
...
]
Collection 2:
user:
_id,
full_name,
username
I am paging through comments via $slice, let's say I take the first 25 entries.
From these entries I need the according usernames, which I receive from the second collection. What I want is to get the comments sorted by their reference username. The problem is I can't add the username to the comments because they may change often and if so, I would need to update all target documents, where the old username was in.
I can only imagine one way to solve this. Read out the entire full_names and query them in the user collection. The result would be sortable but it is not paged and so it takes a lot of resources to do that with large documents.
Is there anything I am missing with this problem?
Thanks in advance
If comments are an embedded array, you will have to do work on the client side to sort the comments array unless you store it in sorted order. Your application requirements for username force you to either read out all of the usernames of the users who commented to do the sort, or to store the username in the comments and have (much) more difficult and expensive updates.
Sorting and pagination don't work unless you can return the documents in sorted order. You should consider a different schema where comments form a separate collection so that you can return them in sorted order and paginate them. Store the username in each comment to facilitate the sort on the MongoDB side. Depending on your application's usage pattern this might work better for you.
It also seems strange to sort on usernames and expect/allow usernames to change frequently. If you could drop these requirements it'd make your life easier :D

Is it possible to get this collection with only one find() call?

i would like to get a collection of documents with a specific one included (i have the _id field of this document).
The difficulty is to also get the 3 documents which precede and follow this document (in the inserting order).
I really doubt it is possible in one request because if i use the where rule to match the id of the document i want to get, i don't know how i could also match the other ones.
So i know i could do one find for the document and get the 3 oldest and newest with another find refering the date of the created_at field, but i am interesting to know if i can improve this treatment.

Fast related tag search in MongoDB

I've got two document sets:
Wikis and WikiTags. Since i want flexible editing of tag names I don't want to embed tag itself into wiki document. So, I store a list of wiki_tag_ids inside wiki document.
I wonder what is the best way to find related tags using this schema. By related tags I mean tags that exist in other wikis tagged with selected tags.
May be I should store related tags in WikiTag document?
I suggest you should store to store WikiTag in Wiki document. Mongodb allow easy update, delete single document from nested collection, thats mean 'flexible editing of tag names'.
Collection like this:
wikis
{
_id,
wikiTags {_id, name, ...},
...
}
So, for example if you want update nested WikiTag name with id = SomeTagId you can:
db.wikis.update( {'wikiTags.id':SomeTagId},
{$set:{'wikiTags.$.name':"New Tag Name"}},
false,
true )
If yoy want delete item from nested array you should use $unset,
add new item: $push, $addToSet
So, i guess now you see that any operation with nested array can be done easy. And if performance is an issue -- use embedding.
Hope this helps.