我是Mongodb的新手,我有两个集合用户和产品。
在产品集合中映射用户ID。产品集合具有productid,producttype,productname和userid作为字段。
我需要写汇总查询
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();
});
});
我已经尝试过了,但是不确定是否正确。
请帮忙。
您所拥有的对于按类型获取产品是正确的。要按用户所在的城市获取产品,请尝试以下管道:
db.products.aggregate([
{
$lookup: {
from: "users",
let: { user_id: "$user_id" },
pipeline: [
{ $match: {
$expr: {
$and: [ { $eq: [ "$_id", "$$user_id" ] },
{ $eq: [ "$city", "new york" ] }]}}}],
as: "user"
}
},
{
$match: {
$expr: { $gt: [ { $size: "$user" }, 0 ] }
}
}
])
测试:https://mongoplayground.net/p/BebeOCd4wLQ
更新:这是另一种方式:
db.products.aggregate([
{
$lookup:
{
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user"
}
},
{
$match: {
"user.city": "new york"
}
},
{
$project: {
user: 0
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句