user6680
user6680

Reputation: 139

Mongoose to count string array inside one document

I'm trying to find a better performing solution maybe where you don't take the whole string array from collection and instead just return the count. Basically the countDocuments equivalent for a string array in one user collection.

I have a solution that works, but if that list gets really long then it won't be as good performance-wise.

                  User.findById(
                  { _id: req.params.id }, { _id: 0 })
                  .select("blacklistGroup").then((result) => {
                    let output = JSON.parse(JSON.stringify(result.blacklistGroup));
                    console.log(output.length + " + people");
                  });

I was hoping to get an example of a more efficient solution more aligned with countDocuments, but for string array. I appreciate the help!

Here is the model definition of blacklistGroup

  blacklistGroup: [String]

collection example

  "blacklistGroup": [
    "5e98e8e785e69146f841d239",
    "5e9867ff5e72550988820dd3",
    "5e98e90d85e69146f841d23a",
    "5e98c950f4fb3f63b4634e30",
    "5e99fcf3a506cf570056898b",
    "5e99fd15a506cf570056898c",
    "5e99fd3aa506cf570056898d",
    "5e99fd64a506cf570056898e",
    "5e99fda5a506cf570056898f"
  ]

Upvotes: 0

Views: 137

Answers (2)

Tina
Tina

Reputation: 534

Try This One:

User.aggregate([
    {
        $match: { _id: req.params.id }
    }, 
    {
        $project: { blacklistGroupLength: { $size: '$blacklistGroup' } }
    }
])

Upvotes: 1

Ricardo
Ricardo

Reputation: 1

I've found something from MongoDB docs that might help you. Here is the link

Upvotes: 0

Related Questions