如何按nodejs&中的标准计算记录MongoDB的

时间:2016-12-24 08:51:48

标签: javascript node.js mongodb

我在mongodb中有以下JSON对象

{
    "_id" : ObjectId("585e34c50ab3cd228a8d6828"),
    "fullname" : "Name1",
    "status" : "INACTIVE",
    "createdDate" : ISODate("2016-12-24T08:41:41.225Z"),
    "updatedDate" : ISODate("2016-12-24T08:41:41.225Z")
},
{
    "_id" : ObjectId("525e34c50ab3cd228a8d6828"),
    "fullname" : "Name2",
    "status" : "ACTIVE",
    "createdDate" : ISODate("2016-12-24T08:41:41.225Z"),
    "updatedDate" : ISODate("2016-12-24T08:41:41.225Z")
}

并且下面的代码返回所有JSON对象的所有计数。

db.collection(col).count(function (err, res) {
     if (err)
         throw err;
     db.close();
});

但我只需要算一下" ACTIVE"状态结果。怎么做?

4 个答案:

答案 0 :(得分:2)

如何:

db.collectionName.find({"status": "ACTIVE"}).count()

我假设你的收藏名称叫做“collectionName”

答案 1 :(得分:1)

试试这个

 db.collection(col).find({"status" : "ACTIVE"}).count(function (err, res) {
     if (err)
        throw err;
     console.log(res)
     db.close();
 });

答案 2 :(得分:1)

db.collection.aggregate(
   [
      { $match: status: "ACTIVE" },
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)

答案 3 :(得分:0)

没有find()

db.collection('anycollection')
    .count( { status : 'ACTIVE' }, (err, count) => {
        console.log(count);
    });

顺便提一下,count()现在已过时,因此将提供更正确的解决方案

db.collection('anycollection)
    .countDocuments( { status : 'ACTIVE' }, (err, count) => {
        console.log(count);
});