I am newbie to mongodb. I need to do a query by reference two collections using dbref and need to query particular fields.
comments collection
{
uid:12345,
pid:444,
comment="blah"
},
{
uid:12345,
pid:888,
comment="asdf"
},
{
uid:99999,
pid:444,
comment="qwer"
}
users collection
{
uid:12345,
name:"john"
},
{
uid:99999,
name:"mia"
}
May I know the command how to insert these collections in mongodb by adding reference between two collections usind dbref? comments in uid must refer the users uid.
Database References (DBRefs) are a convention for storing IDs related to other collections, but are not a feature supported by the MongoDB server (i.e. a "join"). Depending on the language driver you are using to access MongoDB, there may be some support for following DBRefs and fetching the related documents .. but this does involve additional queries, the same as if you did so manually.
So the pseudo code for finding comments related to users in separate collections is something like:
find({..})
users of interest
- For each user found
- ...
find({uid:...})
all comments for that user
Depending on your use case, you may want to consider embedding information rather than linking. For example, the comments
collection may actually be more appropriate embedded inside a posts
collection (each post
on the site has many embedded comments
). Embedded comments could contain some basic user information such as a display name so you do not have to look this up in the users
collection in order to render a page.
For more information see:
MongoDB docs on Schema Design
Designing MongoDB Schemas with Embedded, Non-Embedded and Bucket Structures