Avakash Kumbhar
Avakash Kumbhar

Reputation: 27

Get count of a value of a subdocument inside an array with mongoose

I have Collection of documents with id and contact. Contact is an array which contains subdocuments.

image of the document

I am trying to get the count of contact where isActive = Y. Also need to query the collection based on the id. The entire query can be something like

Select Count(contact.isActive=Y) where _id = '601ad0227b25254647823713'

I am using mongo and mongoose for the first time. Please edit the question if I was not able to explain it properly.

Upvotes: 1

Views: 773

Answers (1)

J.F.
J.F.

Reputation: 15187

You can use an aggregation pipeline like this:

  • First $match to get only documents with desired _id.
  • Then $unwind to get different values inside array.
  • Match again to get the values which isActive value is Y.
  • And $group adding one for each document that exists (i.e. counting documents with isActive= Y). The count is stores in field total.
db.collection.aggregate([
  {
    "$match": {"id": 1}
  },
  {
    "$unwind": "$contact"
  },
  {
    "$match": {"contact.isActive": "Y"}
  },
  {
    "$group": {
      "_id": "$id",
      "total": {"$sum": 1}
    }
  }
])

Example here

Upvotes: 2

Related Questions