mongodb - Meteor Collection: find element in array -


i have no experience nosql. so, think, if try ask code, question can incorrect. instead, let me explain problem.

suppose have e-store. have catalogs

catalogs = new mongo.collection('catalogs); 

and products in catalogs

products = new mongo.collection('products'); 

then, people add there orders temporary collection

order = new mongo.collection(); 

then, people submit comments, phone, etc , order. save collection operations:

operations.insert({   phone: "phone",   comment: "comment",   etc: "etc"   savedorder: order //<- array, right? or object better? }); 

nice, when want stats every product, in operations product have used. how can search thru operations , find every operation product?

or way bad? how real pro's made in real world?

if understand well, here sample document stored in operation collection:

{   clientref: "john-001",   phone: "12345678",   other: "etc.",   savedorder: {       "somemetadataaboutorder": "...",       "lines" : [           { qty: 1, itemref: "xyz001", unitpriceincts: 1050, desc: "usb pen drive 8g" },           { qty: 1, itemref: "abc002", unitpriceincts: 19995, desc: "entry level motherboard" },       ]   } }, {   clientref: "paul-002",   phone: null,   other: "etc.",   savedorder: {       "somemetadataaboutorder": "...",       "lines" : [           { qty: 3, itemref: "xyz001", unitpriceincts: 950, desc: "usb pen drive 8g" },       ]   } }, 

given that, find all operations having item reference xyz001 have query:

> db.operations.find({"savedorder.lines.itemref":"xyz001"}) 

this return whole document. if instead interested in client reference (and operation _id), use projection argument find:

> db.operations.find({"savedorder.lines.itemref":"xyz001"}, {"clientref": 1}) { "_id" : objectid("556f07b5d5f2fb3f94b8c179"), "clientref" : "john-001" } { "_id" : objectid("556f07b5d5f2fb3f94b8c17a"), "clientref" : "paul-002" } 

if need perform multi-documents (incl. multi-embedded documents) operations, should take @ aggregation framework:

for example, calculate total of order:

> db.operations.aggregate([   {$match: { "_id" : objectid("556f07b5d5f2fb3f94b8c179") }},   {$unwind: "$savedorder.lines" },   {$group: { _id: "$_id",               total: {$sum: {$multiply: ["$savedorder.lines.qty",                                          "$savedorder.lines.unitpriceincts"]}}   }} ]) { "_id" : objectid("556f07b5d5f2fb3f94b8c179"), "total" : 21045 } 

Comments