creating and querying a collection in another collection. mongodb node.js - node.js

Is there a way to create and query a collection thats inside another collection...
Can any one direct me to literature that can teach me how to do this?
I've checked the mongodb
docs tutorial and i havent come across this scenario
No code example because i don't know where to start.
Here is what im trying to do.
Im modelling an online shop. So shop object details are in a collection holding many shops.
Now each shop has got products and each product its own unique details. I want to a void using references and rather append but from tutorial from mongodb docs its not quite clear how to do it.
Im fairly new to mongodb
Thanks.

There isn't any such thing as a collection inside another collection with mongo. A collection is a collection of documents.
There are a couple of ways to link documents to other documents, or collections of other data. The correct one to choose is up to you, your data, and your application.
Any document can point to another ObjectId from any field
You can have an array inside a document
Combine the two, and you can have an array of document ids
Mongo is a document store, not a relational database. My suggestion is don't try to use it as a relational database. If what you need is an RDBMS, use one.
Arrays:
http://docs.mongodb.org/manual/reference/operator/query-array/
http://docs.mongodb.org/manual/reference/operator/update-array/
ObjectId:
http://docs.mongodb.org/manual/core/document/

Related

MongoDB - When to add SubDocuments and when to Ref

Im using MongoDB for storing information for a nodeJS application and a doubt came to my mind, after finding that it is possible to use ObjectID to ref another document. As it is known, MongoDB is a no-SQL db, so there is no need for consistency whatsoever and information can be repeated.
So, lets say, I have a collection for users and one of their field values is 'friends', which is an array of this user friends (another users). What is the best practice, saving all the user info there (thus repeating the same thing over and over again throughout the DB) or saving only the ObjectID of the friendUser (makes way more sense to me, but it sounds kinda SQL mindset). I'm not really getting when should I use each of the options, so a professional opinion would be very appreciated.
To model relationships between connected data, you can reference a document or embed it in another document as a subdocument.
Referencing a document does not create a “real” relationship between these two documents as does with a relational database.
Referencing documents is also known as normalization. It is good for data consistency but creates more queries in your system.
Embedding documents is also known as denormalization.
The benefit of Embedding approach is getting all the data you need about a document and it’s sub-document(s) with a single query. Therefore, this approach is very fast. The drawback is that data may not stay as consistent in the database.
Important
If one document is to be used by many documents then better create a referenced doc.
i. Will Save Space.
ii. if any change required, we will have to update only the referenced doc
instead of updating many docs.
Create sub doc(embedded)
i. If another document is not dependent on the subdocument.
Source: https://vegibit.com/mongoose-relationships-tutorial/
Recommended reading:
MongoDB Applied Design Patterns by Rick Copeland
To Embed or Reference

Mongo Collection or Document

I'm looking at the possibility of switching from Filemaker to a MERN app. I get the basic idea of NoSQL databases but its a very different way of thinking. I have recreated what I need in MySQL, but Mongo DB (or Firestore) interests me.
The app is used to record workouts of clients. Each person has many workouts, each workout has many items within it. I'm not sure the best way to do this in Mongo.
I'm between using a collection for all workouts, and each workout has an array of all the items (exercises) they did. Or have the items as a separate collection with a workout_ID to link them up.
Probably the most important thing I'm looking for here is the ability to see all the instances someone did an exercise. From my understanding, if I do it the first way, every single record will be pulled. But the second would only return the documents in that collection that would match exercise_ID and person_ID.
Which is the best approach for such a project?
The second option is the best way to store the data in your case. You can always separate the items in a different collection and store the item Ids in your main collection i.e workouts here.
If you are concerned about querying(joins) them, mongoose provide 'populate' to fetch data between multiple collections using ids as references.
Or you can also use aggregate queries to achieve the same.
hope this helps :)
I think the best option for me would be having an array of the items inside each workout, because that's basically the purpose of using no-SQL databases, to access faster to the data.
However there's a basic rule.. if you think the array of items of each workout it's gonna grow very fast and it will get so big.. then it's better to have a separate collection for the items. if it's not.. then keep those inside an array.
Hope this can be helpful to you.. greetings! :)

Mongoose - How do I query multiple models for an id?

I have models based on schemas, for ex. Users, Events, Rooms. All of these entities can have comments enabled. Comments are stored on a seperate model Comments, since I cannot control how many comments each entity might end up having. I want to be able to Find the entity by id of a comment and make the search through all the models I have. Basically something like this:
[list of models to search].Find( { comment_id: id });
Any ideas?
mongodb can search only one collection per command, so for your use case you would need a separate query for each collection.
You may consider storing all your comments in a single collection and associating them back out to their parent model by reference with modelId and modelName fields. I have used that schema successfully. It sounds like you are storing your comments as an array of comment IDs in your parent model, which seems less practical than either fully embedding the comments or fully separating them.
And there's nothing to stop you from saving the data into multiple collections, so in the 'search' collection and also the separate 'users', 'events' collections.
You might even want to use a technology like solr or elastic search, to index your data.

mongoDB + mongoose: choosing the right schema for hierarchical data

I'm new to mongoDB and in a node project i'm using mongoose to create a schema for my database. I have come to understand that in my case i should be using embedded data instead of by reference. (http://docs.mongodb.org/manual/core/data-modeling-introduction/)
The structure that i need to store in the database is something like this:
book
| title
| | chapter
| | | content (url to a html file)
Coming from a mySQL world, i'm trying to understand the noSQL database concepts and i was wondering how one would design the mongoose schema.
Thx,
You can nest documents, and document arrays in a MongoDB document:
db.books.findOne();
can return a JSON:
{
isbn:"253GHST78F6",
title:"some book",
author:"Earnest Hemmingway",
chapters:[
{title:"chapter 1",content:"http://api.com/chapters/1.html"},
{title:"chapter 2",content:"http://api.com/chapters/2.html"}
]
}
But, there are a few more things to keep in mind when modeling a collection in MongoDB:
Model data as close as possible to what will be asked for: There are no Joins in MongoDB, so, try to keep all such data together (pre joined), that is supposed be queried together in future.
Nesting is good for queries but nested update and search is bad:
Indexing and searching inside nested documents, especially arrays, will be expensive.
Avoid placing any data in nested arrays, that is very frequently updated.
There are no Foriegn Keys in MongoDB. So, if you have multiple copies of same document nested under different collections, keeping all of them updated is your responsibility.
First take a look at this Martin Fowlers excellent video:
I think there is no better authority that can explain nosql, then Fowler. Especially knowing his sql background.
Second, MongoDB follows json schema. If you know how to work with json, you will know how to work with nosql (mongodb). Basic thing that needs to be understand is that Mongo schema is expressed in a language that is using it.
So, if you are using NodeJS with Mongo, you still have objects and array to work with. In simple words, Mongo is not forcing any particular schema. It is on developer to create his scheme based on his language/mongo driver.
So how would you express you data logic in your language ? If it is in form of JS object, then move that form to db.
I really like MongoDB, becuse it can be combined with some great JS tools like Underscore.js for all kind of data manipulations.

Link two document with native driver

I have two different collections in my database, and at this point I need to link a document from first collection to a document form second collection with native NodeJs driver.
How can I do that? Should I hold the _id from first collection in second collection?
Yes, I would suggest storing the _id of the related document, manually, as you described. I've done that a lot, and it works well.
A more complex (and seemingly unnecessary in the case you describe), would be to use a DBRef.

Resources