【问题标题】:Aggregate Query in MongoDb with Node JS使用 Node JS 在 MongoDb 中聚合查询
【发布时间】:2020-02-22 04:19:42
【问题描述】:

我是 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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 2014-03-19
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多