In MongoDB, how do we apply filter criteria on a subdocument

Viewed 25

I have the below collection called "Survey" having 1000 documents out of which i am taking 2 as an example here.

[
  {
    "_id": ObjectId("5a934e000102030405000007"),
     "name": "Asger systems",
    "content": [
      {
        "content_id": ObjectId("5a934e000102030405000000"),
        "placebo": true,
        "type": "tt"
      },
      {
        "content_id": ObjectId("5a934e000102030405000002"),
        "placebo": false,
        "type": "pp"
      }
    ]
  },
  {
    "_id": ObjectId("5a934e000102030405000008"),
    "name": "DCCC here it goes",
    "content": [
      {
        "content_id": ObjectId("5a934e000102030405000001"),
        "placebo": false,
        "type": "cc"
      },
      {
        "content_id": ObjectId("5a934e000102030405000000"),
        "placebo": true,
        "type": "Multiple"
      }
    ]
  }
]

Now i actually want to "Find the percentage of surveys (which have "DCCC" in the name) that have at least one content which has content type = Multiple"

I am able to build the query for counting the total number of documents and then filtering for name using db.Survey.find( { name: { $regex: /DCCC/ } } ).countDocuments() but now i am confused as in how will i filter a subdocument which is a value inside type field. Also, i am not sure how will i find the percentage.Please help and tell me if i am in the right direction or not.

1 Answers

To filter the document with at least one element with { type: "Multiple" } in content array, you can use dot notation as below:

db.Survey.find({
  name: {
    $regex: /DCCC/
  },
  "content.type": "Multiple"
})

Demo @ Mongo Playground

While performing the percentage of surveys, the formula:

percentage = (number of filtered document(s) / total number of documents) * 100

Hence, it would be something like:

let filteredCount = db.Survey.find({
  name: {
    $regex: "DCCC"
  },
  "content.type": "Multiple"
}).countDocuments();

let totalCount = db.Survey.find({}).countDocuments();

let percentage = (filteredCount / totalCount) * 100;
Related