mongodb - 使用 Node JS 在 MongoDb 中聚合查询
问题描述
我是 Mongodb 的新手。我有两个集合用户和产品。
在产品集合中映射了用户 ID。产品集合具有 productid、producttype、productname 和 userid 作为字段。
我需要编写聚合查询
- 使用聚合查询根据“product_type”获取所有产品并填充用户(必须使用聚合查询)
- 使用聚合查询根据用户城市获取所有产品(必须使用聚合查询)
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
}
}
])
推荐阅读
- postgresql - 如何在 postgres 中启用索引顺序文件
- sql - 使用具有相似列的两个表进行 SELECT 或 JOIN
- python - 使用递归找到一对中的目标差异
- javascript - 在给定时间间隔后取消角色
- asp.net - 在 IIS 中托管的 Asp.net C# Web 应用程序中打印到客户端打印机
- android - 应用程序因 base.apk!libmonochrome.so 而崩溃
- python - 我的 Python 程序说“AttributeError: 'str' object has no attribute 'encode' on line 4”
- php - 使用 DomDocument 将 HTML、CSS 和 JavaScript 从文件中分离出来
- google-api - Google API 访问令牌含义
- php - 以编程方式为 WooCommerce 中的特定可变产品设置最小、最大和步长数量