mjoyce91
mjoyce91

Reputation: 326

MongoDB - Using Aggregate to get more than one Matching Object in an Array

I'm trying to do exactly what the poster in this link was trying to accomplish. I have documents with the same structure as the poster; in my documents there is an array of objects, each with many keys. I want to bring back all objects (not just the first, as you can with an $elemMatch) in that array where a key's value matches my query. I want my query's result to simply be an array of objects, where there is a key in each object that matches my query. For example, in the case of the linked question, I would want to return an array of objects where "class":"s2". I would want returned:

"FilterMetric" : [ 
              {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s2"
              }, 
              {
                "min" : "0.00",
                "max" : "16.83",
                "avg" : "0.00",
                "class" : "s2"
              } 
                ]

I tried all the queries in the answer. The first two queries bring back an empty array in robomongo. In the shell, the command does nothing and return me to the next line. Here's a screenshot of robomongo:

enter image description here

On the third query in the answer, I get an unexpected token for the line where "input" is.

I'm using MongoDB version 3.0.2. It appears as if the OP was successful with the answer, so I'm wondering if there is a version issue, or if I'm approaching this the wrong way.

Upvotes: 1

Views: 604

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311875

The only problem with the answers in that question seems to be that they're using the wrong casing for FilterMetric. For example, this works:

db.sample.aggregate([
    { "$match": { "FilterMetric.class": "s2" } },
    { "$unwind": "$FilterMetric" },
    { "$match": { "FilterMetric.class": "s2" } },
    { "$group": {
        "_id": "$_id",
        "FilterMetric": { "$push": "$FilterMetric" }
    }}
])

Upvotes: 1

Related Questions