0

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"
  ]

2 Answers 2

1

Try This One:

User.aggregate([
    {
        $match: { _id: req.params.id }
    }, 
    {
        $project: { blacklistGroupLength: { $size: '$blacklistGroup' } }
    }
])
Sign up to request clarification or add additional context in comments.

2 Comments

I added this, but console.log(res) outputs []. It should say 10 pastebin.com/3w9BNVgE
I got it working, but had to add mongoose.Types.ObjectId(req.params.id)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.