0

I have a short but important question. I am new to MongoDB and querying.

My database looks like the following: I only have one document stored in my database (sorry for blurring).

The document consists of different fields:

  • two are blurred and not important
  • datum -> date
  • instance -> Array with an Embedded Document Object; Our instance has an id, two not important fields and a code.

My Document

Now I want to query how many times an object in my instance array has the group "a" and a text "sample"?

Is this even possible?

I only found methods to count how many documents have something...

I am using Mongo Compass, but i can also use Pymongo, Mongoengine or every other different tool for querying the mongodb.

Thank you in advance and if you have more questions please leave a comment!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
slaayaah
  • 101
  • 1
  • 2
  • 8

1 Answers1

1

You can try this

db.collection.aggregate([
  {
    $unwind: "$instance"
  },
  {
    $unwind: "$instance.label"
  },
  {
    $match: {
      "instance.label.group": "a",
      "instance.label.text": "sample",

    }
  },
  {
    $group: {
      _id: {
        group: "$instance.label.group",
        text: "$instance.label.text"
      },
      count: {
        $sum: 1
      }
    }
  }
])
Ghazanfar Khan
  • 3,648
  • 8
  • 44
  • 89
  • this is almost correct. But I also get: {sum:1} and this result is not correct. It should be around 20 (in my case). Does it really counts how often there is an instance with group "a" and text "sample"? @GhanzanfarKhan – slaayaah Apr 03 '20 at 15:55
  • Yes it will count the groups on a and text sample – Ghazanfar Khan Apr 03 '20 at 20:11
  • i had to delete the group stage to get the correct answer, but then it did work – slaayaah Apr 04 '20 at 11:11