1

I have data like this:

{
  "profileID": "123456789",
  "myArray": [
    {
      "read": false
    },
    {
      "read": true
    },
    {
      "read": false
    },
    {
      "read": true
    }
  ]
}

I want to be able to get the count of: myArray where read is false. I need to do this on Mongoose. In the example above, the return I want is 2.

My findOne is like below:

userModel.findOne({'profileID': 123456789}, function(err, myArray) {
    //Code to run here
});

I can manually run through the response and make my count that way but that will be very ineffeciant.

How do I get the count of the user's myArray's unread values on the database level?

Thanks

0

1 Answer 1

2

You should use aggregate:

> db.bla.insert({
...   "profileID": "123456789",
...   "myArray": [
...     {
...       "read": false
...     },
...     {
...       "read": true
...     },
...     {
...       "read": false
...     },
...     {
...       "read": true
...     }
...   ]
... })
WriteResult({ "nInserted" : 1 })

> db.bla.aggregate([{$match:{"profileID":"123456789"}}, {$unwind:"$myArray"}, {$match:{"myArray.read":false}}, {$count:"unread_mail"}])
{ "unread_mail" : 2 }

You can then $unwind your array to do your count.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm mate! Initially I had an issue with $count but then I looked up the documentation for Mongo that it was introduced in version 3.4 and I was on version 3.2.x So all good after the upgrade. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.