I am new to Mongodb.i have two collections users and products.
In product collection user id is mapped.product collection has productid,producttype,productname and userid as fields.
i need to write aggregate query
- Use aggregate query to get all the products based on “product_type” and populate user (Aggregate query must be used)
- Use aggregate query to get all the product based on the user city (Aggregate query must be used)
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("demo1");
dbo
.collection("products")
.aggregate([{
$match: {
product_type: "$product_type"
}
},
{
$lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "userdetails"
}
}
])
.toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});
I have tried this but not sure if this is right.
Please help.