I'm building an app where employees can be added to the database and each employee belongs to a particular company, which can be chosen from a select field on the form. The form to add employees also contains a salary field and I would like to be able to display the companies with their total salary expense (based on the sum of salaries of its employees).
At first, I imagined I would use a single "employees" collection. Then, for example, choose "Apple" as the company, and finally, in the end, I would end up with a list of employee objects where I can loop through all the employees where "Apple" was the company and sum all the salary fields. This ended up being a poor approach. Next, I decided to create a separate collection of "companies". Then, before saving an employee, I look up the company object ID, and save that as the company.
For instance,
{ firstName: "Bob", lastName, "Smith", company: "5b62a456e7179a07334478a5", salary: 7}
Where "5b62a456e7179a07334478a5" is the "_id" field of Apple.
How do I continue to define this relationship in MongoDB?
Do I add an employees field to each company and try to save each employee to a company upon saving them to the employee's collection? In this way, I can try to access the sum of all employees within each company to obtain a total salary expense.
But I would then have to write to two different collections each time a new employee is saved. Also, what would the flow of that even look like? I would need to use the company _id field to look up the company and then save the employee to the company. So, would I have to perform a query and two writes on each new employee save?
You can use the lookup feature to do a "join"
db.table1.aggregate([{
$lookup: {
from: "table2",
localField: "table2column",
foreignField: "table1key",
as: "alias"
},
{
$project:{
//columns you want
}
}
}])
That being said...if your data is relational and not obscenely huge, a relational database might be a better choice.
Related
my website takes a dataset and the dataset contains data about a students or employees..etc, so I want to display the column names to the user.
Is there a way to pull the fields name?
ex:
Name, Age, Country
String, Number, String
Fahad, 13, riyadh
Jane, 27, United Kingdom
Andrew, 29 , United States
Mary, 19 , France
I want to display "Name" "Age" "Country" to the user
I'm using node.js mongoose.
If your documents have similar structure, why not just
Object.keys(db.your_collection.findOne())
for more accurate u need use the lean() method because it will
POJO values else it will return mongodb instance keys instead of document keys.
Object.keys(db.your_collection.findOne().lean())
I have a requirement to filter some records on the basis of period for example get me all products count between 201704 and 201705.
So my emit is something like:
emit([doc.productId, doc.period],1)
and reduce used is _count. But when i am trying to filter on startkey and endkey it gives me all records. I am trying something like:
startkey=["201604"]&endkey=[{},"201605"]
where my key structure is something like key:
[
"aws-60826348802",
201703
]
I dont want to reverse the order of elements in key as i want a count on ids by defining the group_level=1. Could anyone help me out. I did not get any solution yet.
In order to be able to select (with startkey/endkey), your index needs to be in in that order. Let's say your docs look like this:
{
"_id": "someid",
"product": "aws-60826348802",
"date": "201604",
"price": 42.42
}
You could create a map function to index the documents in date order like so:
function(doc) {
emit([doc.date, doc.product], doc.price);
}
You now have a two-dimensional key (on date & product code) and the value is emitted is the price.
This allows you to select items by date:
?startkey=["201604"] // find items where the date is >= 201604
?startkey=["201604"]&endkey=["201605"] // find items in April 2016
if you choose a reducer (_count, _sum, or _stats) you can also perform aggregation:
?startkey=["201601"]&endkey=["201701"]&group_level=1 // find items in 2016, group by month
?startkey=["201601"]&endkey=["201701"]&group_level=2 // find items in 2016, grouped by month and product code
This could get you monthly totals of product sales, for example.
I have a table with order records for each Product Type. The columns contain information like Order Number, Customer Name, Product Category, Product, and Order Receipt Date.
My goal is to find the quantity of orders that fall into the below conditions:
New Customers Ordering any Product Category for the First Time
Existing Customers Ordering from any Product Category for the First Time
Reorders from any Product Category
What would be the best way to go about this?
Think I figured it out:
I created two columns for records: "First Product Type Order?" and "First Order?"
"First_Product_Type_Order": IF(AND(Order2=Order1,Product_Type2=Product_Type1),First_Product_Type_Order1,IF(SUMPRODUCT(($Customer$2:$Customer2=D2)*($Product_Type$2:$Product_Type2=Product_Type2))>1,"Reorder","First Time Order"))
"First_Order":
IF(Order2=Order1,First_Order1,IF(SUMPRODUCT(($Customer$2:$Customer2=Customer2)*1)>1,"Existing Customer","New Customer"))
I have this excel sheet and I want to migrate it to Access (in the near future some other DB manager) And I don't know how to normalize it exactly, I know this might be very opinion base. Currently they use this table for inventory
This is the original Table (sheet)
"TableName: Parts", Fields:"Id_Part", "No_Part", "No_Mold", "No_Lot", "Rev", "Description", "Area", "No_Job", No_Batch,"OrderDate","RecivedDate"
Explanation of problem:
ok the idea is to create a DB that stores all the part numbers the "x" company has, these part numbers have the corresponding field:
1.- Id_Part : is the unique number for each part.
2.- No_Part: Number part of each part that the company uses for there products.
3.- No_Mold: Each Part Number uses a Molding Item, some part numbers use the same Molding Item.
4.- No_Lot: The Lot Number is to keep track of the part numbers in case the client has some issues with the final product. (Its like a tracking number).
5.- Rev: is for Revision control example: A, B or C.
6.- Description: Describes the part number.
7.- Area: name of the department in with the part number is used ( like a type of Part Number).
8.-No_Batch: Its similar to the Lot number, but its an internal number for the company.
9.- Order Date: Date in witch we ordered a part number form a provider.
10.- Received Date: Date when we get that part number from the provider.
This is how I tried to Normalize it
Table1 Name: Parts
Fields: Id_Part, No_Part, Id_Mold, Id_Lot, Id_Rev, Id_Description, Id_Area, Id_job,
Id_Batch, Date_Order, Date_Recived.
Table2 Name: Areas
Fields: Id_Area, Name
Table3: Molds
Fields: Id_Mold, No_Mold, Id_Part
Table4:Jobs
Fields: Id_Job, No_Job
Tablr5:Batchs
Fields: Id_Batch, No_Batch
Table6 Name: descriptions
Fields:Id_Description,Description,Id_Part
Table7 Name:Rev
Fields: Id_Rev,Rev,Id_Part
Any help is useful.
It seems like the PartRevision is the main table here rather than the part. You don't order a Honda Accord, you order a 2013 Honda Accord.
You purchase a PartRevision and it goes into a batch and a lot. You sell a part revision and it pulls from a batch and a lot. Here's how I'd set it up.
In my model I have:
Product <<---> Order
Product Attributes:
productName
productPrice
Product Relationships:
order
Order Attributes:
orderName
salePerson
Order Relationships:
products
Imagine I have a Product (call it product1):
productName: MacBook
productPrice: 1200
The application in general used to sale products.
So after add and done the sale. Automatically create an Order (call it currentOrder) which contain product1.
[currentOrder addProductsObject:product1];
Next I changed product1 price to:
productPrice: 1000
After I recheck the product inside the currentOrder, I'll see the productPrice is UPDATED to: 1000
Which I need to not change and still be exactly like the previous (1200).
Basically I would to do something do NOT update the previous object.
Your business model is not suitable for your case. You need to have another entity 'Sale' or so. Your model should look like: Order <--->>Sale, Product <---> Sale. Product Attributes: productName. Order Attributes: orderName salePerson Order Relationships: sales. Save Attributes: productPrice Sale Relationships: order. So in this way you decouple price from product and will be able store different prices in different orders.