如何使用nodejs和mongodb获取每个类别中的产品数量

时间:2017-10-30 23:54:23

标签: node.js mongodb

我是新手nodejs和mongodb。我该怎么办:

我想获得每个类别的产品数量;

class ObjCache() {
    constructor() {
        this.cache = new Map();
    }
    get(id) {
        let cacheItem = this.cache.get(id);
        if (cacheItem) {
            ++cacheItem.refCnt;
            if (cacheItem.obj) {
                // already have the object
                return Promise.resolve(cacheItem.obj);
            }
            else {
                // object is pending, return the promise
                return cacheItem.promise;
            }
        } else {
            // not in the cache yet
            let cacheItem = {refCnt: 1, promise: null, obj: null};
            let p = myDB.get(id).then(function(obj) {
                // replace placeholder promise with actual object
                cacheItem.obj = obj;
                cacheItem.promise = null;
                return obj;
            });
            // set placeholder as promise for others to find
            cacheItem.promise = p;
            this.cache.set(id, cacheItem);
            return p;

        }
    }
    release(id) {
        let cacheItem = this.cache.get(id);
        if (cacheItem) {
            if (--cacheItem.refCnt === 0) {
                this.cache.delete(id);
            }
        }
    }
}

...

当我尝试在nodejs中查询时,我想获取(id,name,number_of_product)。

cate1(id, name) :
+ product 1(id,name,cate ,created_by)
+ product 2(id,name,cate ,created_by)
+ product 3(id,name,cate ,created_by)
+ product 4(id,name,cate ,created_by)

cate2(id, name) :
+ product 5(id,name,cate ,created_by)
+ product 6(id,name,cate ,created_by)
+ product 7(id,name,cate ,created_by)
+ product 8(id,name,cate ,created_by)
+ product 9(id,name,cate ,created_by)

我该怎么做?

我在mysql中有一个查询:

=> cate1 has 4 products
=> cate2 has 5 products

我可以得到:

Select cate.id, cate.name, count(*) totalCount 
from cate, product 
where cate.id = 1 and product.cate = 1

有人可以翻译成nodejs和mongodb。

谢谢!

2 个答案:

答案 0 :(得分:0)

Mongo shell

db.categories.aggregate([
    {
        $lookup:
        {
            from: 'products',
            localField: "_id",
            foreignField: "category_id",
            as: 'products'
        }
    },
    {
        $project:
        {
            _id: 1,
            name: 1,
            number_of_product: { $size: "$products" }
        }
    }
]);

<强> MongoClient

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/db', function(err, db) {
    if (err) throw err;
    var collection = db.collection('categories');
    collection.aggregate([
        {
            $lookup:
            {
                from: 'products',
                localField: "_id",
                foreignField: "category_id",
                as: 'products'
            }
        },
        {
            $project:
            {
                _id: 1,
                name: 1,
                number_of_product: { $size: "$products" }
            }
        }
    ], function(err, result) {
        if (err) throw err;
        console.log(result);
    });
});

<强>猫鼬

Category.aggregate([
    {
        $lookup:
        {
            from: 'products',
            localField: "_id",
            foreignField: "category_id",
            as: 'products'
        }
    },
    {
        $project:
        {
            _id: 1,
            name: 1,
            number_of_product: { $size: "$products" }
        }
    }
]).exec(function(err, result) {
    if (err) throw err;
    console.log(result);
});

说明:查找阶段将对产品集合执行左外连接,结果是一个类别列表,其中产品分组在数组中,然后它来到$ project阶段,它选择字段我们需要或我们想要从现有领域计算。 $ size运算符将计算产品数组的长度

答案 1 :(得分:0)

嗨, 我想,这就是你真正想要的。

Category.aggregate(
    [
      {
        $lookup: {
          from: "products",
          localField: "_id",
          foreignField: "category_id",
          as: "products"
        }
      },
      {
        $project:
        {
          _id: 1,
          category: 1,
          totalProducts: {$size: "$products"},
          products: "$products"
        }
      }
    ]
  ).exec(function(err, results) {
    if (err) {
      throw err;
    }
    res.end("" + JSON.stringify({data: results}));
  });