mongodb - How to populate two collections data together like Joins in SQL -
i'm new mongodb. want result showing 2 collections data joins in sql. here, below scenario can pull table2
's data.
can have both tables data displayed?
var courseids = db.getcollection('table1').find( { studentid: '347765' } ).map(function(cid){ return cid.courseid; }); db.getcollection('table2').find({ cid : {$in: courseids}}, {name: 1, course: 1});
mongo not relational database, can try aggregate collections lookup. using example documentation, because unfortunately did not give structure of table1 , table2 , connecting field.
a collection orders contains following documents:
{ "_id" : 1, item" : "abc", "price" : 12, "quantity" : 2 } { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 } { "_id" : 3 }
another collection inventory contains following documents:
{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 } { "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 } { "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 } { "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 } { "_id" : 5, "sku": null, description: "incomplete" } { "_id" : 6 }
the following aggregation operation on orders collection joins documents orders documents inventory collection using fields item orders collection , sku field inventory collection:
db.orders.aggregate([ { $lookup: { from: "inventory", localfield: "item", foreignfield: "sku", as: "inventory_docs" } } ])
please see https://docs.mongodb.com/manual/reference/operator/aggregation/lookup further information. please check general documentation: recommend avoid joins.
wiki
Comments
Post a Comment