首页 > 解决方案 > 使用 Node JS 在 MongoDb 中聚合查询

问题描述

我是 Mongodb 的新手。我有两个集合用户和产品。

在产品集合中映射了用户 ID。产品集合具有 productid、producttype、productname 和 userid 作为字段。

我需要编写聚合查询

  1. 使用聚合查询根据“product_type”获取所有产品并填充用户(必须使用聚合查询)
  2. 使用聚合查询根据用户城市获取所有产品(必须使用聚合查询)

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();
    });
});

我已经尝试过了,但不确定这是否正确。

请帮忙。

标签: mongodb

解决方案


您所拥有的对于按类型获取产品是正确的。要按用户所在城市获取产品,请尝试以下管道:

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
        }
    }
])

推荐阅读