MongoDB - How to query multiple attributes within an object and group results

I am trying to learn MongoDB and I cannot figure out how to do this.

Let's say I have three objects:

         {
            "_id": 99990,
            "type" : 15,
            "attributes": [
                {
                    "id": 1,
                    "value": 115
                }
            ]
        },
        {
            "_id": 99991,
            "type" : 5,
            "attributes": [
                {
                    "id": 1,
                    "value": 120
                }
            ]
        },
        {
            "_id": 99992,
            "type" : 5,
            "attributes": [
                {
                    "id": 1,
                    "value": 120
                }
            ]
        },
        {
            "_id": 99993,
            "type" : 5,
            "attributes": [
                {
                    "id": 1,
                    "value": 150
                }
            ]
        },

How can I search for elements and only return id 99993 based on the id attribute 1 with a value of 150? I just started playing with MongoDB today, so this is probably a very simple question.

To add to the problem, how can I group the results for each element of type 5 using the / id / value attributes and get the result, for example:

 "id" : 1, "value" : 150, "count" : 1
 "id" : 1, "value" : 120: "count" : 2

This is just an example of data, the scheme is quite complicated, but for this exercise it should be enough.

+3
source share
1 answer

For the first part, you can get this entry by doing:

db.collectionName.find({"attributes.id": 1, "attributes.value": 150});

_id , id = 1 = 150.

, map-reduce. Mongo.

+4

All Articles