4

I would like to return specific fields from an array in Mongo and am having trouble.

Let us say we have a document like such:

{
  "student":"Bob",
  "report_cards": [
    {
      "Year":2016,
      "English":"B",
      "Math":"A"
    },
    {
      "Year":2015,
      "English":"B",
      "Math":"A"
    }
  ]
}

I would like to return the following:

{"Student": "Bob", {"English":"B"}}

Basically, I only need the first element in the report cards array, and only return the English field.

I know it is something around:

db.collection.find({},{"Student":1, "report_cards":{$slice:1}});

But this, of course, results in the full array (year, english, math) returning. I have tried the following:

db.collection.find({},{"Student":1, "report_cards.$.english":{$slice:1}})
db.collection.find({},{"Student":1, "report_cards":{$slice:1, "$.english"}});

but those aren't correct.

How do I simply return one field from the obj within the array results?

Thank you!

0

2 Answers 2

3

You can use the aggregation framework to get the values as

db.test.aggregate
([{$project:{_id:0,
student:'$student',
English:{ $arrayElemAt: ['$report_cards.English',0]
}}}])
Sign up to request clarification or add additional context in comments.

Comments

1

AFAIK there is no built-in operator for filtering key value pair in embedded documents.

You can use combination of operators to achieve in latest 3.4 version.

The below query use $arrayElemAt to get first element in report_cards followed by $objectToArray to convert to array-view ( array of k and v pairs ) and $filter on English key to keep the matching key value pair and $arrayToObject to convert back to document.

Something like

{
  "$project": {
    "output": {
      "$arrayToObject": {
        "input": {
          "$filter": {
            "input": {
              "$objectToArray": {
                "$arrayElemAt": [
                  "$report_cards",
                  0
                ]
              }
            },
            "as": "result",
            "cond": {
              "$eq": [
                "$$result.k",
                "English"
              ]
            }
          }
        }
      }
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.