2
_id:5e4d18bd10e5482eb623c6e4
notification_obj:
 0  notification_text:"Welcome to the app and your account is created hello."
    open:false
    type:"just_click"

 1  notification_text:"Sebal started following you."
    open:true
    type:"open_profile"

 2  notification_text:"Hella started following you."
    open:false
    type:"open_profile"

So here I have an array 'notification_obj' array in a document of mongo database, I want to search the record with _id and in that record I want to count 'How many 'open:false' values are there. I want to count in this array that open:false how many times. Please help with a "query" in mongo db.

6
  • do a find query on the collection and then get the document/record and then do Array.filter and find the length of filtered array Commented Feb 22, 2020 at 2:57
  • How about some help with Aggregation function. I don't want to get the complete array from database. I want a query for mongo db. Commented Feb 22, 2020 at 3:02
  • Does this answer your question? Mongoose / MongoDB: count elements in array Commented Feb 22, 2020 at 3:04
  • @technophyle no this one is different. First I want to search the collection with _id and in that record I want to count number of true values in an array. Commented Feb 22, 2020 at 3:08
  • I know, but you can investigate the aggregate query in that answer and I believe you can achieve what you want with a small change. Hint: unwind. Commented Feb 22, 2020 at 3:08

1 Answer 1

4

I think this code help you.

db.getCollection('your_collection').aggregate([
  {
    $match: { _id: ObjectId("5a544.............") }
  },
  {
    $unwind: '$notification_obj'
  },
  {
    $match: { 'notification_obj.open': false }
  },
  {
    $count: 'total'
  }
]);

Output:

{
    "total" : 1
}
Sign up to request clarification or add additional context in comments.

1 Comment

Had to change some things but this is the answer I was looking for thanks mayur.

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.