admin管理员组

文章数量:1356595

I have the following JSON object in mongodb

{
    "_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")
}

and the codes below return all count of all JSON objects.

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

but i need to count only "ACTIVE" status results. How to do that?

I have the following JSON object in mongodb

{
    "_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")
}

and the codes below return all count of all JSON objects.

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

but i need to count only "ACTIVE" status results. How to do that?

Share Improve this question asked Dec 24, 2016 at 8:51 digitdigit 4,5653 gold badges29 silver badges45 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

how about just:

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

Im assuming your collection name is called "collectionName"

try this

 db.collection(col).find({"status" : "ACTIVE"}).count(function (err, res) {
     if (err)
        throw err;
     console.log(res)
     db.close();
 });
db.collection.aggregate(
   [
      { $match: status: "ACTIVE" },
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)

without find()

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

By the way , count() is deprecated now so more correct solution would be

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

本文标签: javascriptHow to count records by criteria in nodejs amp mongodbStack Overflow